如何使用Yii::app()->end()方法,它与exit()有什么区别?

16
在表单验证中,我发现了这样的代码。
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
    {
        echo CActiveForm::validate($model);
        Yii::app()->end();
    }

手册上说,end()方法将终止应用程序。 为什么要终止应用程序?以下代码不会执行吗?

2个回答

21

是的,这是一个Ajax请求,代码应该返回验证结果然后停止代码执行。这与Php die函数的想法相同,但允许Yii运行onApplicationEnd清理代码(如果有)。


完成操作后会运行什么其他代码?无论如何,应用程序都会停止。还是说? - Racky
@racky 请看我的回答。可以为应用程序编写其他操作的行为,如记录日志、数据库清理等。 - acorncom
@acorncom,如果Yii::app()->end()在事务之间发生,那么在onApplicationEnd期间它会自动回滚吗? - fortm
@fortm 不要相信这个,不可能的。 - acorncom

3

简单地说,它只是终止应用程序。与php的exit()不同的是,在退出之前调用了onEndRequest()

尽管文档中表示status参数0表示正常退出,而其他值表示异常退出,但实际上并不是这样实践的。 status参数只是简单地传递给exit()函数(当然输出它!)。

Yii::app()->end('saved', true);

甚至对象也可以按如下方式输出:

Yii::app()->end(json_encode($data), true);

注意:(1)onEndRequest()会在应用程序处理请求后立即触发。此函数可用于提示日志和其他有用的功能。

Yii框架end()函数文档

/**
* Terminates the application.
* This method replaces PHP's exit() function by calling
* {@link onEndRequest} before exiting.
* @param integer $status exit status (value 0 means normal exit while other values mean abnormal exit).
* @param boolean $exit whether to exit the current request. This parameter has been available since version 1.1.5.
* It defaults to true, meaning the PHP's exit() function will be called at the end of this method.
*/

public function end($status=0,$exit=true)
{
if($this->hasEventHandler('onEndRequest'))
$this->onEndRequest(new CEvent($this));
if($exit)
exit($status);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接