13 php yii magic-methods yii-components
突击队需要你的帮助.
我在Yii有一个控制器:
class PageController extends Controller {
public function actionSOMETHING_MAGIC($pagename) {
// Commando will to rendering,etc from here
}
}
Run Code Online (Sandbox Code Playgroud)
我需要在Yii CController下使用一些神奇的方法来控制/ page ||下的所有子请求 页面控制器.
这是Yii的某种可能吗?
谢谢!
Jon*_*Jon 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)));
}
Run Code Online (Sandbox Code Playgroud)
您可以简单地用例如替换它
public function missingAction($actionID)
{
echo 'You are trying to execute action: '.$actionID;
}
Run Code Online (Sandbox Code Playgroud)
在上面,$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;
}
}
Run Code Online (Sandbox Code Playgroud)
例如,你可以做一些像笨手笨脚的事情
public function createAction($actionID)
{
return new CInlineAction($this, 'commonHandler');
}
public function commonHandler()
{
// This, and only this, will now be called for *all* pages
}
Run Code Online (Sandbox Code Playgroud)
或者你可以根据你的要求做一些更精细的事情.
bri*_*iiC 10
你的意思是CController或Controller(最后一个是你的扩展类)?如果您像这样扩展CController类:
class Controller extends CController {
public function beforeAction($pagename) {
//doSomeMagicBeforeEveryPageRequest();
}
}
Run Code Online (Sandbox Code Playgroud)
你可以得到你需要的东西