Yii cannot Instantiate controller

2019-04-30 05:22发布

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?

2条回答
啃猪蹄的小仙女
2楼-- · 2019-04-30 05:58

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()

查看更多
Melony?
3楼-- · 2019-04-30 06:05

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

查看更多
登录 后发表回答