【问题标题】:Yii's magic method for controlling all actions under a controllerYii 控制一个控制器下所有动作的神奇方法
【发布时间】:2011-09-15 02:22:10
【问题描述】:

突击队需要你的帮助。

我在 Yii 中有一个控制器:

class PageController extends Controller {
    public function actionSOMETHING_MAGIC($pagename) {
        // Commando will to rendering,etc from here
    }
}

我需要一些 Yii CController 下的魔术方法来控制 /page 下的所有子请求 ||页面控制器。

这在 Yii 中是否可行?

谢谢!

【问题讨论】:

    标签: php yii yii-components magic-methods


    【解决方案1】:

    当然有。最简单的方法是覆盖missingAction 方法。

    这是默认实现:

    public function missingAction($actionID)
    {
        throw new CHttpException(404,Yii::t('yii','The system is unable to find the requested action "{action}".',
            array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
    }
    

    你可以简单地用例如替换它

    public function missingAction($actionID)
    {
        echo 'You are trying to execute action: '.$actionID;
    }
    

    在上面,$actionID 就是你所说的$pageName

    一个稍微复杂但也更强大的方法是覆盖createAction 方法。这是默认实现:

    /**
     * Creates the action instance based on the action name.
     * The action can be either an inline action or an object.
     * The latter is created by looking up the action map specified in {@link actions}.
     * @param string $actionID ID of the action. If empty, the {@link defaultAction default action} will be used.
     * @return CAction the action instance, null if the action does not exist.
     * @see actions
     */
    public function createAction($actionID)
    {
        if($actionID==='')
            $actionID=$this->defaultAction;
        if(method_exists($this,'action'.$actionID) && strcasecmp($actionID,'s')) // we have actions method
            return new CInlineAction($this,$actionID);
        else
        {
            $action=$this->createActionFromMap($this->actions(),$actionID,$actionID);
            if($action!==null && !method_exists($action,'run'))
                    throw new CException(Yii::t('yii', 'Action class {class} must implement the "run" method.', array('{class}'=>get_class($action))));
            return $action;
        }
    }
    

    例如,在这里,你可以做一些严厉的事情

    public function createAction($actionID)
    {
        return new CInlineAction($this, 'commonHandler');
    }
    
    public function commonHandler()
    {
        // This, and only this, will now be called for  *all* pages
    }
    

    或者你可以根据你的要求做一些更精细的事情。

    【讨论】:

      【解决方案2】:

      您的意思是 CController 或 Controller(最后一个是您的扩展类)? 如果你像这样扩展 CController 类:

      class Controller extends CController {
         public function beforeAction($pagename) {
      
           //doSomeMagicBeforeEveryPageRequest();
      
         }
      }
      

      你可以得到你需要的东西

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多