怎么向controller中加入成员?

在Yii类里面重写了一些逻辑

但是不知道怎么才能向controller中加入数据

我该怎么做?

加入数据?你的意思是,建一些变量?

直接声明就可以了吧。

应该说不是,我是想在app已经生成,但是还没有run的时候给controller加入一些成员

extends CController

components/Controller.php文件里声明就行!

这样所有的控制器都可以用

大概只能这样,因为在没有run的时候,控制器还没初始化呢,只能暂存在app或者其他类里面

谢谢各位

我还有一个问题,就是 如果createwebapplication后,不运行run,而是runController($route),这会不会错过什么重要的东西?

虽然在测试中还没有遇到什么问题,但还是有点不放心。

你指的是修改入口文件吗?

是的,在入口处(Yii),修改了一些逻辑,那里有些代码修改route信息(我想一定有更好的办法,而不需要像我这样蛮干)

然后就是runcontroller($route)了

你说一下这样做有什么意图呢?为什么先runController($route)呢?

因为我要把yii当作一个程序的一部分,这个程序在一定的时候调用yii,而不想每调用一次就初始化一次,就通过传递route进行(希望有更好的方式)

run的话我不知道怎么传递route,而runcontroller可以接受route就可以以此为据创建controller调用action了

yii是自动加载类啊!在对象初始化的时候才该类会被包含进来,现在基于PHP5的框架都是autoload,你如果不放心,可以看一下运行的日志就知道了

不是这个意思啦,我是想知道,run()一直运行到runController()之间都做了 除了处理route之外的什么事?。

感觉应该不会出什么事,可能会丢失一些事件。。

我运行index.php以后前几条日志如下:

Loading "log" application component

Loading "request" application component

Loading "urlManager" application component

Loading "cache" application component

Serving "Yii.CUrlManager.rules" from cache

Loading "db" application component

Opening DB connection

…

接下来是model的一些查询日志

…

Loading "clientScript" application component

Loading "user" application component

Loading "session" application component

Loading "assetManager" application component

当处理用户请求时,应用将经历如下声明周期:

1.通过 CApplication::preinit() 预初始化应用;

2.设置类的自动装载器和错误处理;

3.注册核心类组件;

4.加载应用配置;

5.通过 CApplication::init() 初始化应用:

•注册应用行为;

•载入静态应用组件;

6.触发 onBeginRequest 事件;

7.处理用户请求:

•解析用户请求;

•创建控制器;

•运行控制器;

8.触发 onEndRequest 事件。

•解析用户请求;

就是这一步我自己处理了,也许我需要的就是onbeginrequest事件。

然后就是如何在错误发生(如404)后,不是直接运行一个action后退出,而是可以交给其它程序呢?

默认生成的代码的错误页面是site/error,你可以在siteController的actionError里做处理

如果你只是对404页面做处理,那么你可以判断一下


public function actionError()

	{

	    if($error=Yii::app()->errorHandler->error)

	    {

	    	if(Yii::app()->request->isAjaxRequest)

	    		echo $error['message'];

	    	else

	        	$this->render('error', $error);

	    }

	}

error property read-only (available since v1.0.6)

public array getError()

code - the HTTP status code (e.g. 403, 500)

type - the error type (e.g. ‘CHttpException’, ‘PHP Error’)

message - the error message

file - the name of the PHP script file where the error occurs

line - the line number of the code where the error occurs

trace - the call stack of the error

source - the context source code where the error occurs

你可以用$error=Yii::app()->errorHandler->error;

$error[‘code’]去判断错误代码!

直接取好像也没用?

因为最终的处理都传递到errorHandler,可能需要做一下CErrorHandler的继承。

暂时没有其他问题了,接下来面对的可能是效率上的问题。。

感谢 巡洋艦 , 大好人 :D

呵呵,互相帮助啊!刚开始我也遇到了好多问题,大家互相交流一下就会解决了!

又有一个问题,现在的Yii在运行完一个controller后,会进行销毁处理吗?

因为程序里会多次创建controller,如果没有我该怎么进行最后的处理呢?