Die magische Methode von YII zur Kontrolle aller Aktionen unter einem Controller
-
28-10-2019 - |
Frage
Kommando braucht Hilfe von dir.
Ich habe einen Controller in yii:
class PageController extends Controller {
public function actionSOMETHING_MAGIC($pagename) {
// Commando will to rendering,etc from here
}
}
Ich brauche eine magische Methode unter yii controller, um alle Unterrequest unter /Seite zu kontrollieren || Seitencontroller.
Ist das mit YII irgendwie möglich?
Vielen Dank!
Lösung
Sicher gibt es. Der einfachste Weg ist es, die zu überschreiben missingAction
Methode.
Hier ist die Standardimplementierung:
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)));
}
Sie könnten es einfach durch EG ersetzen
public function missingAction($actionID)
{
echo 'You are trying to execute action: '.$actionID;
}
In obigem, $actionID
ist das, was Sie als bezeichnen $pageName
.
Ein etwas engagierterer, aber auch leistungsfähigerer Ansatz wäre es, das überschreiben createAction
Methode stattdessen. Hier ist die Standardimplementierung:
/**
* 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;
}
}
Hier können Sie zum Beispiel etwas so hartnäckig tun wie
public function createAction($actionID)
{
return new CInlineAction($this, 'commonHandler');
}
public function commonHandler()
{
// This, and only this, will now be called for *all* pages
}
Oder Sie könnten nach Ihren Anforderungen etwas ausgefeilteres tun.
Andere Tipps
Sie meinen controller oder controller (letztes ist Ihre erweiterte Klasse)? Wenn Sie die Controller -Klasse wie folgt erweitert haben:
class Controller extends CController {
public function beforeAction($pagename) {
//doSomeMagicBeforeEveryPageRequest();
}
}
Sie könnten bekommen, was Sie brauchen