2013-04-25 88 views
1

假设我有一些类可以使用MVC。控制器的基类有一个构造函数和析构函数。如何知道什么时候在析构函数中引发异常php

class BaseController { 
    public function __construct() { 
     ob_start(); 

    } 

    # Some code here. 

    public function __destruct() { 
     if(!error_get_last()) { 
      if(!$this->doNotOutputBuffer) { 
       $controllerContent = ob_get_contents(); 
       ob_clean(); 
       $this->_template->render($this->_appinfo['directory'], $this->templateOptions, $controllerContent); 
      } else { 
       $this->_template->render($this->_appinfo['directory'], $this->templateOptions); 
      } 
     } 
    } 
} 

注意每个功能ob_star()和ob_clean()的存在,它应该视图数据传递给模板类来渲染与模板的意见。当抛出异常时,我会在LoginController之外的“TryCatch”块中捕获错误,但总是调用析构函数,error_get_last()函数返回NULL,无论如何,即使存在错误,视图也将被加载。

class LoginController extends BaseController{ 

    public function __construct() { 
     parent::__construct(); 
    } 

    public function main() {  
     throw new Exception("Error Fatal..."); 
    } 

    public function __destruct() { 
     parent::__destruct(); 
    } 

} 

我怎么能知道什么时候发生异常不显示视图?

回答

0

添加标志和包装方法。

class LoginController extends BaseController{ 

    private $_is_throwed = false; 

    public function __construct() { 
     parent::__construct(); 
    } 

    public function main() { 
     try{ 
      $this->_main(); 
     } catch (Exception $e) { 
      $this->_is_throwed = true; 
      throw $e; 
     } 
    } 

    private function _main() { 
     throw new Exception("Error Fatal..."); 
    } 

    public function __destruct() { 
     if (!$this->_is_throwed) { 
      parent::__destruct(); 
     } else { 
      ob_clean(); 
     } 
    } 

} 

P.S.但要注意在破坏中使用逻辑,它可能会导致麻烦。

相关问题