Yii2 - 如何自动加载自定义类? [英] Yii2 - How do I AutoLoad a custom class?

查看:30
本文介绍了Yii2 - 如何自动加载自定义类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下要在 Yii2 应用程序中使用的自定义类:

I have created the following custom class that I'd like to use in my Yii2 application:

@common/components/helper/CustomDateTime.php

namespace common\components\helper;
class CustomDateTime{function Now() {...}}

我想像这样使用这个类:

I want to use this class like this:

public function actionDelete($id)
{
    $account = $this->findModel($id);
    $account->archived = 1;
    $account->archived_date = CustomDateTime::Now();
    $account->save();

    return $this->redirect(['index']);
}

在我的@common/config/bootstrap.php 文件中,我根据这个 http://www.yiiframework.com/doc-2.0/guide-concept-autoloading.html.

In my @common/config/bootstrap.php file I've created a classMap according to this http://www.yiiframework.com/doc-2.0/guide-concept-autoloading.html.

Yii::$classMap['CustomDateTime'] = '@common/components/helper/CustomDateTime.php';

但我收到错误:未找到 Class 'app\controllers\myapp\CustomDateTime'

问题:如何创建 classMap 以便不必在每个控制器的开头使用 use 语句来访问我的自定义类?

QUESTION: How do I create a classMap so that I don't have to use the use statement at the beginning of every controller to access my custom class?

Yii 1.1 曾经在配置文件中有一个选项来导入"一组代码,以便在调用时自动加载类文件.

Yii 1.1 used to have an option in the config file to 'import' a set of code so that a class file could be autoloaded when it was called.

解决方案

非常感谢@Animir 将我重定向回原始文档.http://www.yiiframework.com/doc-2.0/guide-concept-autoloading.html.

Many thanks to @Animir for redirecting me back to the original documentation. http://www.yiiframework.com/doc-2.0/guide-concept-autoloading.html.

我发现我可以在我的 @common/config/bootstrap.php 文件中使用以下内容

I found that I can use the following in my @common/config/bootstrap.php file

Yii::$classMap['CustomDateTime'] = '@common/components/helper/CustomDateTime.php';

但是 - 它仅在 CustomDateTime.php 文件没有声明的命名空间时才有效.

BUT - it only works when the the CustomDateTime.php file does NOT have a declared namespace.

//namespace common\components\helper;
class CustomDateTime{function Now() {...}}

推荐答案

只需在文件中添加 use 语句,在你使用类的地方.

Just add use statement in file, where you use a class.

use common\components\helper\CustomDateTime;
/* some code */
public function actionDelete($id)
{
    $dateNow = CustomDateTime::Now();
    /* some code */
}
/* some code */

这篇关于Yii2 - 如何自动加载自定义类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆