Yii cannot Instantiate controller

家住魔仙堡 提交于 2020-01-23 07:08:07

问题


As I see if we want to instantiate a Model (for example named Post), we just have to call:

$post = new Post();

Now, I also want to instantiate a Controller (for example named Post, and php file for this controller named PostController.php). So I use this code:

$postController = new PostController();

However, I get an error when running this code.

I did some searching and found that it should be like the following to instantiate:

$postController = Yii::app()->createController('post/index');

It runs correctly. But I still wonder why the first approach doesn't work?


回答1:


Answering your exact question "why the first approach doesn't work". The folder /protected/controller is NOT in "include path" of the project.

Just add 'import'=>array('application.controllers.*') into your config file or use include(Yii::app()->getBasePath().DIRECTORY_SEPARATOR.'controllers'.DIRECTORY_SEPARATOR.'PostController.php');

just before creating an object of PostController. Ah and creating new controller requires a name for this controller, so it should be something like

$controller = new PostController('post_controller');

I would like to point out that this type of controller creation is useless in Yii, as you are creating a controller completely separated from project, so it will be almost useless. As you noted, the correct way to create controller is through Yii::app()->createController()




回答2:


Just use:

 $controller = Yii::app()->controller;

This returns your current controller for request.

Also see docs here: http://www.yiiframework.com/doc/api/1.1/CApplication#controller-detail



来源:https://stackoverflow.com/questions/11771141/yii-cannot-instantiate-controller

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!