5

正如我所看到的,如果我们想实例化一个模型(例如命名Post),我们只需要调用:

$post = new Post();

现在,我还想实例化一个Controller(例如 namedPost和这个控制器的 php 文件PostController.php)。所以我使用这段代码:

$postController = new PostController();

但是,运行此代码时出现错误。

我做了一些搜索,发现实例化应该如下所示:

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

它运行正确。但我仍然想知道为什么第一种方法不起作用?

4

2 回答 2

6

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

于 2012-08-02T07:46:33.863 回答
1

只需使用:

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

这将返回您当前的控制器以供请求。

另请参阅此处的文档:http ://www.yiiframework.com/doc/api/1.1/CApplication#controller-detail

于 2012-08-02T06:28:48.323 回答