Yii 无法实例化控制器 [英] Yii cannot Instantiate controller

查看:26
本文介绍了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,以及名为 PostController.php 的控制器的 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 对象之前.啊,创建新的控制器需要这个控制器的名字,所以它应该像

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天全站免登陆