コントローラーの下ですべてのアクションを制御するためのYiiの魔法方法

StackOverflow https://stackoverflow.com/questions/6350769

質問

コマンドーはあなたからの助けを必要としています。

私はYiiにコントローラーを持っています:

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

/ページのすべてのサブレクエストを制御するために、Yii ccontrollerの下で魔法の方法が必要です||ページコントローラー。

これは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
}

または、要件に応じて、より詳細なことをすることができます。

他のヒント

Controllerまたはコントローラー(最後の1つは拡張クラスです)を意味しますか?このようなccontrollerクラスを拡張した場合:

class Controller extends CController {
   public function beforeAction($pagename) {

     //doSomeMagicBeforeEveryPageRequest();

   }
}

必要なものを手に入れることができます

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top