In View(CakePHP), the proper way to get current controller?

前端 未结 8 985
伪装坚强ぢ
伪装坚强ぢ 2021-02-02 07:36

In View, I can get action by using

$this->action

But, I cannot get controller name by

$this->controller
8条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-02 08:00

    All the other solutions are to get the controller name... I need the controller itself, so I did the following function in an AdminHelper.php called by $this->Admin->_getController('MyControllerName') into the view.ctp file

    /******************************************************************
     * 
     ******************************************************************/
    function _getController( $pControllerName ){
        if ( ! isset($this->controllersArray[$pControllerName]) ){
            $importRes = App::import('Controller', $pControllerName);// The same as require('controllers/users_controller.php');
            $strToEval = "\$controller = new ".$pControllerName."Controller;";
            $evalRes = eval($strToEval);
            if ( $evalRes === false ){
                throw new AppException("Eval returned an error into ".__FILE__." getController()");
            }
            $controller->constructClasses();// If we want the model associations, components, etc to be loaded
            $this->controllersArray[$pControllerName] = $controller;
        }
    
        $result = $this->controllersArray[$pControllerName];
        return $result;
    }
    

    Note: don't forget to declare it into the controller you'll use for example:

    • people/view.ctp -> $this->Admin->_getController('MyControllerName')
    • PeopleController.ctp -> var $helpers = array('Html', 'Form', 'Admin');
    • AdminHelper.ctp -> function _getController(...

提交回复
热议问题