Yii不能实例化控制器 [英] Yii cannot Instantiate controller

查看:368
本文介绍了Yii不能实例化控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我看到我们想实例化一个模型(例如名为 Post )时,我们只需要调用:

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

$post = new Post();

现在,我还想实例化一个 Controller (例如命名为 Post ,并且此控制器的php文件名为 PostController.php )。所以我使用这个代码:

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?

推荐答案

回答你的确切问题为什么第一种方法不工作。
文件夹 / protected / controller 在项目的包含路径中为 NOT

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

只需将'import'=> array('application.controllers。*')添加到您的配置文件或使用
include(Yii :: app() - > getBasePath()。DIRECTORY_SEPARATOR.'controllers'.DIRECTORY_SEPARATOR.'PostController.php');

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

就是在创建PostController对象之前。 Ah和创建新的控制器需要这个控制器的名称,所以它应该是像

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');

我想指出,这种类型的控制器创建在Yii中是无用的,因为你创建一个完全独立于项目的控制器,因此它将几乎无用。正如你所说,创建控制器的正确方法是通过 Yii :: app() - > createController()

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

这篇关于Yii不能实例化控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆