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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With