Yii2 - 如何自动加载自定义类?

时间:2015-01-30 02:44:46

标签: php yii2

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

@公共/组件/辅助/ CustomDateTime.php

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

我想像这样使用这个类:

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创建了一个classMap。

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

但是我收到错误: Class'apps \ controllers \ myapp \ CustomDateTime'找不到

问题:如何创建一个classMap,这样我就不必在每个控制器的开头使用 use 语句来访问我的自定义类? / p>

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';

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

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

4 个答案:

答案 0 :(得分:5)

只需在文件中添加use语句,即使用类。

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

答案 1 :(得分:4)

您也可以this方式进行操作,而无需使用return 0;

use

但为了成功完成这件事,你可以在下面添加Yii::$app->cdt->Now(); // cdt - CustomDateTime(配置文件)

app/config/web.php

答案 2 :(得分:0)

Yii 2中的自动加载非常简单。您可以通过使用config主文件加载类来使用它。像

您已在components / helper / CustomDateTime.php中创建了您的类。现在在文件顶部的config / main.php中添加以下代码

require_once( dirname(__FILE__) . '/../components/helper/CustomDateTime.php');

现在,您的课程在您的项目中自动加载,您可以在其中使用它,就像您在控制器,模型或视图中一样使用

只需像这样使用

CustomDateTime-><methodName>();

试试这个我在我的项目中使用过它。

您可以使用此链接进行参考。点击here

答案 3 :(得分:0)

我知道问这个问题已经很久了。我偶然发现了这一点,并分享了我的所作所为。

我通常在use语句之后使用别名,而不是为每个模型或类对象添加100行使用语句。在我看来,为你使用的许多类添加classMap并不是一个好主意。如果你这样做,即使你没有使用这些对象,你也只是添加不必要的映射。

这就是我做的事情

use Yii;
use common\helpers as Helper;
use yii\helpers as YiiHelper;
use common\models as Model;
use common\components as Component;

在控制器中

public function actionIndex(){
   $model = Model\SomeModel();

   if(Yii::$app->request->isPost){
       $post = Yii::$app->request->post('SomeModel');
       $model->text = Helper\Text::clean($post['text']);
       $model->text = YiiHelper\Html::encode($model->text);

       if($model->save()){
           return $this->render('thank_you');
       }
   }
}

希望这会有所帮助:)