php - Yii 在一个 Controller 下控制所有 Action 的神奇方法

标签 php yii yii-components magic-methods

突击队需要你的帮助。

我在 Yii 中有一个 Controller :

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

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

这在某种程度上可以用 Yii 实现吗?

谢谢!

最佳答案

当然有。最简单的方法是覆盖 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
}

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

关于php - Yii 在一个 Controller 下控制所有 Action 的神奇方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6350769/

相关文章:

javascript - booster 在 yii 中通过 jquery 发生冲突

yii - 如何从 url 中查找 YII 路由

yii - Yii2如何将用户密码以Hash格式保存到DB中

php - Yii 交易和验证问题

yii - 如何禁用 CGridView 中列的排序?

php - Linux PDF to HTML + Image Map + jpeg 图像文件

php - 将闭包作为新方法绑定(bind)到类

php - linux ubuntu 18.04 灯 php 和 python cgi

php - 使用单个公共(public)列计算 SQL 表中唯一行的数量

php - 如何为 CListView 的最后一项设置 css 样式?