Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii cannot Instantiate controller

Tags:

controller

yii

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?

like image 800
Lebarn Avatar asked Aug 02 '12 04:08

Lebarn


Video Answer


1 Answers

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

like image 83
Johnatan Avatar answered Oct 05 '22 03:10

Johnatan