Question

l'aide de Commando besoin de vous.

J'ai un contrôleur Yii:

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

J'ai besoin d'une méthode magique sous Yii CController pour contrôler tous subrequest sous / page || le contrôleur.

Est-ce possible avec une certaine façon Yii?

Merci!

Était-ce utile?

La solution

Bien sûr, il est. Le plus simple est de remplacer la méthode missingAction.

Voici l'implémentation par défaut:

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)));
}

vous pouvez simplement le remplacer par par exemple.

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

Dans ce qui précède, $actionID est ce que vous appelez $pageName.

Une approche un peu plus complexe, mais aussi plus puissant serait de remplacer la méthode createAction à la place. Voici l'implémentation par défaut:

/**
 * 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;
    }
}

Ici par exemple, vous pouvez faire quelque chose comme la main lourde, comme

public function createAction($actionID)
{
    return new CInlineAction($this, 'commonHandler');
}

public function commonHandler()
{
    // This, and only this, will now be called for  *all* pages
}

Ou vous pourriez faire quelque chose de façon plus élaborée, selon vos besoins.

Autres conseils

Vous voulez dire CController ou Controller (dernier est votre classe étendue)? Si vous avez étendu la classe CController comme ceci:

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

     //doSomeMagicBeforeEveryPageRequest();

   }
}

vous pouvez obtenir ce dont vous avez besoin

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top