在 CakePHP 中的所有控制器之前检查状态的常用方法

common method to check status before all controllers in CakePHP

我在 cakephp 中有一个应用程序,其中登录用户的状态必须为 active,否则它应该重定向到用户必须提交其应用程序的控制器。

实际上,我想在所有控制器上实现,每当用户尝试访问任何控制器操作时,它应该自动检查状态,如果状态不活动,它应该重定向到用户应用程序。我如何在 Appcontroller.

中实现它

我的 Appcontroller 内容是:

public function initialize()
    {
        parent::initialize();

        $this->loadComponent('RequestHandler', [
            'enableBeforeRedirect' => false,
        ]);
        $this->loadComponent('Flash');
        $this->loadComponent('Auth', [
            'authError' => 'You have been logged out due to period of inactivity.',
            'loginAction' => [
                'controller' => 'Users',
                'action' => 'login'
            ],
            'loginRedirect' => [
                'controller' => 'Users',
                'action' => 'dashboard'
            ],
            'logoutRedirect' => [
                'controller' => 'Users',
                'action' => 'logout'
            ],
        ]);

您可以在 AppController 中使用 beforeFilter 方法来执行此类检查。 假设您要重定向到的控制器的名称是 YourController,那么您的方法应该如下所示。

    public function beforeFilter( $event ) {

        if ($this->Auth->user()) { //If User is logged in.
            if ( $this->request->controller != 'YourController' ) { //If Request Controller is other than YourController
                $status  = $this->Auth->user('status'); //Get the Status
                if( $status != 'active' ) { //If Status is not active
                    //Redirect Here
                    return $this->redirect(
                        ['controller' => 'YourController', 'action' => 'index'];
                    );                  
                }   
            }
        }
    }