我创建了以下自定义类,我想在我的Yii2应用程序中使用它:
@普通/组件/帮手/ CustomDateTime.php
namespace common\components\helper;
class CustomDateTime{function Now() {...}}
Run Code Online (Sandbox Code Playgroud)
我想像这样使用这个类:
public function actionDelete($id)
{
$account = $this->findModel($id);
$account->archived = 1;
$account->archived_date = CustomDateTime::Now();
$account->save();
return $this->redirect(['index']);
}
Run Code Online (Sandbox Code Playgroud)
在我的@common/config/bootstrap.php文件中,我根据http://www.yiiframework.com/doc-2.0/guide-concept-autoloading.html创建了一个classMap .
Yii::$classMap['CustomDateTime'] = '@common/components/helper/CustomDateTime.php';
Run Code Online (Sandbox Code Playgroud)
但我收到错误:找不到类'app\controllers\myapp\CustomDateTime'
问题:如何创建一个classMap,这样我就不必在每个控制器的开头使用use语句来访问我的自定义类?
Yii 1.1曾经在配置文件中有一个选项来"导入"一组代码,以便在调用类文件时可以自动加载它.
解
非常感谢@Animir将我重新引导回原始文档. http://www.yiiframework.com/doc-2.0/guide-concept-autoloading.html.
我发现我可以在@ common/config/bootstrap.php文件中使用以下内容
Yii::$classMap['CustomDateTime'] = '@common/components/helper/CustomDateTime.php';
Run Code Online (Sandbox Code Playgroud)
但是 - 它仅在CustomDateTime.php文件没有声明的命名空间时才有效.
//namespace common\components\helper;
class CustomDateTime{function Now() {...}}
Run Code Online (Sandbox Code Playgroud)
只需use在文件中添加语句,即使用类.
use common\components\helper\CustomDateTime;
/* some code */
public function actionDelete($id)
{
$dateNow = CustomDateTime::Now();
/* some code */
}
/* some code */
Run Code Online (Sandbox Code Playgroud)