【问题标题】:Cake: Access the controller in a static method in a componentCake:在组件中以静态方法访问控制器
【发布时间】:2014-02-13 08:23:26
【问题描述】:

我们在 Cake 组件中有一个静态方法。如果此组件引发特定错误,则任务是将用户重定向到登录页面。当前(工作)解决方案是:

class SomeComponent extends Component {

    static $controllerObject; 

    function startup(&$controller) {        
        SomeComponent::$controllerObject =& $controller;
    }

(...)

    public static function decodeResponse($response) {
        if($response == null || trim($response) == '') {
            return null;
        }
        $result = json_decode($response, true);
        if($result == null) {
            throw new FatalErrorException('Could not parse api server response: ' . $response);
        }
        if(isset($result['error'])) {
            if ($result['error'] === "IncorrectCredentialsException") {
                self::$controllerObject->Session->destroy();                
                self::$controllerObject->Session->setFlash(__('Your session has ended. Please log in again.', true), 'default', array(), 'error');                                
                self::$controllerObject->redirect(array(
                    'language' => Configure::read('Config.language'),
                    'controller' => 'users', 
                    'action' => 'login'
                )); 

            }
            else { throw new ApiServerException($result); }
        }
        return $result;
    }

但是,我负责软件质量的团队同事认为这个解决方案并不令人满意。他说:“请找到一种更好的方法将控制器传递给解码方法。将控制器设置为静态变量并不是最好的方法”。

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: cakephp cakephp-2.4


    【解决方案1】:

    我认为问题在于您的方法做了两件事:解码和错误处理。我不会在您的方法中处理IncorrectCredentialsException,而是将此功能移动到您处理其他异常的位置,然后在您的方法中抛出一个IncorrectCredentialsException。通过此更改,您不再需要在静态方法中访问控制器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-16
      • 2012-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-30
      相关资源
      最近更新 更多