13

コマンドーはあなたからの助けが必要です。

Yiiにコントローラーがあります:

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

/ page ||の下のすべてのサブリクエストを制御するために、YiiCControllerの下にいくつかの魔法のメソッドが必要です。ページコントローラー。

これはYiiでどういうわけか可能ですか?

ありがとう!

4

2 に答える 2

19

確かにあります。最も簡単な方法は、メソッドをオーバーライドする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
}

または、要件に応じて、より複雑なことを行うこともできます。

于 2011-07-04T10:58:26.080 に答える
10

CController または Controller (最後のものは拡張クラスです) のことですか? 次のように CController クラスを拡張した場合:

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

     //doSomeMagicBeforeEveryPageRequest();

   }
}

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

于 2011-06-15T07:31:15.553 に答える