CController

优质
小牛编辑
129浏览
2023-12-01
所有包 | 属性 | 方法
system.web
继承class CController » CBaseController » CComponent
子类CCodeGenerator, CExtController
源自1.0
版本$Id: CController.php 3515 2011-12-28 12:29:24Z mdomba $
源码framework/web/CController.php
CController manages a set of actions which deal with the corresponding user requests.

Through the actions, CController coordinates the data flow between models and views.

When a user requests an action 'XYZ', CController will do one of the following: 1. Method-based action: call method 'actionXYZ' if it exists; 2. Class-based action: create an instance of class 'XYZ' if the class is found in the action class map (specified via actions(), and execute the action; 3. Call missingAction(), which by default will raise a 404 HTTP exception.

If the user does not specify an action, CController will run the action specified by defaultAction, instead.

CController may be configured to execute filters before and after running actions. Filters preprocess/postprocess the user request/response and may quit executing actions if needed. They are executed in the order they are specified. If during the execution, any of the filters returns true, the rest filters and the action will no longer get executed.

Filters can be individual objects, or methods defined in the controller class. They are specified by overriding filters() method. The following is an example of the filter specification:
array(  'accessControl - login',  'ajaxOnly + search',  array(      'COutputCache + list',      'duration'=>300,  ),
)
The above example declares three filters: accessControl, ajaxOnly, COutputCache. The first two are method-based filters (defined in CController), which refer to filtering methods in the controller class; while the last refers to a object-based filter whose class is 'system.web.widgets.COutputCache' and the 'duration' property is initialized as 300 (s).

For method-based filters, a method named 'filterXYZ($filterChain)' in the controller class will be executed, where 'XYZ' stands for the filter name as specified in filters(). Note, inside the filter method, you must call $filterChain->run() if the action should be executed. Otherwise, the filtering process would stop at this filter.

Filters can be specified so that they are executed only when running certain actions. For method-based filters, this is done by using '+' and '-' operators in the filter specification. The '+' operator means the filter runs only when the specified actions are requested; while the '-' operator means the filter runs only when the requested action is not among those actions. For object-based filters, the '+' and '-' operators are following the class name.

公共属性

隐藏继承属性

属性类型描述定义在
actionCActionthe action currently being executed, null if no active action.CController
actionParamsarrayReturns the request parameters that will be used for action parameter binding.CController
cachingStackCStackstack of COutputCache objectsCController
clipsCMapReturns the list of clips.CController
defaultActionstringthe name of the default action.CController
idstringID of the controllerCController
layoutmixedthe name of the layout to be applied to this controller's views.CController
moduleCWebModulethe module that this controller belongs to.CController
pageTitlestringthe page title.CController
routestringthe route (module ID, controller ID and action ID) of the current request.CController
uniqueIdstringthe controller ID that is prefixed with the module ID (if any).CController
viewPathstringReturns the directory containing view files for this controller.CController

公共方法

隐藏继承方法

方法描述定义在
__call()如果类中没有调的方法名,则调用这个方法。CComponent
__construct()CController
__get()返回一个属性值、一个事件处理程序列表或一个行为名称。CComponent
__isset()检查一个属性是否为null。CComponent
__set()设置一个组件的属性值。CComponent
__unset()设置一个组件的属性为null。CComponent
accessRules()Returns the access rules for this controller.CController
actions()Returns a list of external action classes.CController
asa()返回这个名字的行为对象。CComponent
attachBehavior()附加一个行为到组件。CComponent
attachBehaviors()附加一个行为列表到组件。CComponent
attachEventHandler()为事件附加一个事件处理程序。CComponent
beginCache()Begins fragment caching.CBaseController
beginClip()Begins recording a clip.CBaseController
beginContent()Begins the rendering of content that is to be decorated by the specified view.CBaseController
beginWidget()Creates a widget and executes it.CBaseController
behaviors()Returns a list of behaviors that this controller should behave as.CController
canGetProperty()确定属性是否可读。CComponent
canSetProperty()确定属性是否可写。CComponent
clearPageStates()Removes all page states.CController
createAbsoluteUrl()Creates an absolute URL for the specified action defined in this controller.CController
createAction()Creates the action instance based on the action name.CController
createUrl()Creates a relative URL for the specified action defined in this controller.CController
createWidget()Creates a widget and initializes it.CBaseController
detachBehavior()从组件中分离一个行为。CComponent
detachBehaviors()从组件中分离所有行为。CComponent
detachEventHandler()分离一个存在的事件处理程序。CComponent
disableBehavior()禁用一个附加行为。CComponent
disableBehaviors()禁用组件附加的所有行为。CComponent
enableBehavior()启用一个附加行为。CComponent
enableBehaviors()启用组件附加的所有行为。CComponent
endCache()Ends fragment caching.CBaseController
endClip()Ends recording a clip.CBaseController
endContent()Ends the rendering of content.CBaseController
endWidget()Ends the execution of the named widget.CBaseController
evaluateExpression()计算一个PHP表达式,或根据组件上下文执行回调。CComponent
filterAccessControl()The filter method for 'accessControl' filter.CController
filterAjaxOnly()The filter method for 'ajaxOnly' filter.CController
filterPostOnly()The filter method for 'postOnly' filter.CController
filters()Returns the filter configurations.CController
forward()Processes the request using another controller action.CController
getAction()返回the action currently being executed, null if no active action.CController
getActionParams()Returns the request parameters that will be used for action parameter binding.CController
getCachingStack()返回stack of COutputCache objectsCController
getClips()Returns the list of clips.CController
getEventHandlers()返回一个事件的附加处理程序列表。CComponent
getId()返回ID of the controllerCController
getLayoutFile()Looks for the layout view script based on the layout name.CController
getModule()返回the module that this controller belongs to. It returns null if the controller does not belong to any moduleCController
getPageState()Returns a persistent page state value.CController
getPageTitle()返回the page title. Defaults to the controller name and the action name.CController
getRoute()返回the route (module ID, controller ID and action ID) of the current request.CController
getUniqueId()返回the controller ID that is prefixed with the module ID (if any).CController
getViewFile()Looks for the view file according to the given view name.CController
getViewPath()Returns the directory containing view files for this controller.CController
hasEvent()确定一个事件是否定义。CComponent
hasEventHandler()检查事件是否有附加的处理程序。CComponent
hasProperty()确定属性是否被定义。CComponent
init()Initializes the controller.CController
invalidActionParams()This method is invoked when the request parameters do not satisfy the requirement of the specified action.CController
isCachingStackEmpty()Returns whether the caching stack is empty.CController
missingAction()Handles the request whose action is not recognized.CController
processDynamicOutput()Postprocesses the dynamic output.CController
processOutput()Postprocesses the output generated by render().CController
raiseEvent()发起一个事件。CComponent
recordCachingAction()Records a method call when an output cache is in effect.CController
redirect()Redirects the browser to the specified URL or route (controller/action).CController
refresh()Refreshes the current page.CController
render()Renders a view with a layout.CController
renderClip()Renders a named clip with the supplied parameters.CController
renderDynamic()Renders dynamic content returned by the specified callback.CController
renderDynamicInternal()This method is internally used.CController
renderFile()Renders a view file.CBaseController
renderInternal()Renders a view file.CBaseController
renderPartial()Renders a view.CController
renderText()Renders a static text string.CController
resolveViewFile()Finds a view file based on its name.CController
run()Runs the named action.CController
runAction()Runs the action after passing through all filters.CController
runActionWithFilters()Runs an action with the specified filters.CController
setAction()设置the action currently being executed.CController
setPageState()Saves a persistent page state value.CController
setPageTitle()设置the page title.CController
widget()Creates a widget and executes it.CBaseController

受保护方法

隐藏继承方法

方法描述定义在
afterAction()This method is invoked right after an action is executed.CController
afterRender()This method is invoked after the specified is rendered by calling render().CController
beforeAction()This method is invoked right before an action is to be executed (after all possible filters.)CController
beforeRender()This method is invoked at the beginning of render().CController
createActionFromMap()Creates the action instance based on the action map.CController
loadPageStates()Loads page states from a hidden input.CController
replaceDynamicOutput()Replaces the dynamic content placeholders with actual content.CController
savePageStates()Saves page states as a base64 string.CController

属性详细

action 属性 public CAction getAction()
public void setAction(CAction $value)

the action currently being executed, null if no active action.

actionParams 属性 只读 (可用自 v1.1.7) public array getActionParams()

Returns the request parameters that will be used for action parameter binding. By default, this method will return $_GET. You may override this method if you want to use other request parameters (e.g. $_GET+$_POST).

cachingStack 属性 只读 public CStack getCachingStack(boolean $createIfNull=true)

stack of COutputCache objects

clips 属性 只读 public CMap getClips()

Returns the list of clips. A clip is a named piece of rendering result that can be inserted at different places.

参见

  • CClipWidget
defaultAction 属性 public string $defaultAction;

the name of the default action. Defaults to 'index'.

id 属性 只读 public string getId()

ID of the controller

layout 属性 public mixed $layout;

the name of the layout to be applied to this controller's views. Defaults to null, meaning the application layout is used. If it is false, no layout will be applied. The module layout will be used if the controller belongs to a module and this layout property is null.

module 属性 只读 public CWebModule getModule()

the module that this controller belongs to. It returns null if the controller does not belong to any module

pageTitle 属性 public string getPageTitle()
public void setPageTitle(string $value)

the page title. Defaults to the controller name and the action name.

route 属性 只读 (可用自 v1.1.0) public string getRoute()

the route (module ID, controller ID and action ID) of the current request.

uniqueId 属性 只读 public string getUniqueId()

the controller ID that is prefixed with the module ID (if any).

viewPath 属性 只读 public string getViewPath()

Returns the directory containing view files for this controller. The default implementation returns 'protected/views/ControllerID'. Child classes may override this method to use customized view path. If the controller belongs to a module, the default view path is the module view path appended with the controller ID.

方法详细

__construct() 方法
public void __construct(string $id, CWebModule $module=NULL)
$idstringid of this controller
$moduleCWebModulethe module that this controller belongs to.
源码: framework/web/CController.php#111 (显示) publicfunction__construct($id,$module=null)
{
$this->_id=$id;
$this->_module=$module;
$this->attachBehaviors($this->behaviors());
}
accessRules() 方法
public array accessRules()
{return}arraylist of access rules. See CAccessControlFilter for details about rule specification.
源码: framework/web/CController.php#244 (显示) publicfunctionaccessRules()
{
returnarray();
}

Returns the access rules for this controller. Override this method if you use the accessControl filter.

actions() 方法
public array actions()
{return}arraylist of external action classes
源码: framework/web/CController.php#209 (显示) publicfunctionactions()
{
returnarray();
}

Returns a list of external action classes. Array keys are action IDs, and array values are the corresponding action class in dot syntax (e.g. 'edit'=>'application.controllers.article.EditArticle') or arrays representing the configuration of the actions, such as the following,

return array(  'action1'=>'path.to.Action1Class',  'action2'=>array(      'class'=>'path.to.Action2Class',      'property1'=>'value1',      'property2'=>'value2',  ),
);
Derived classes may override this method to declare external actions.

Note, in order to inherit actions defined in the parent class, a child class needs to merge the parent actions with child actions using functions like array_merge().

You may import actions from an action provider (such as a widget, see CWidget::actions), like the following:
return array(  ...other actions...  // import actions declared in ProviderClass::actions()  // the action IDs will be prefixed with 'pro.'  'pro.'=>'path.to.ProviderClass',  // similar as above except that the imported actions are  // configured with the specified initial property values  'pro2.'=>array(      'class'=>'path.to.ProviderClass',      'action1'=>array(          'property1'=>'value1',      ),      'action2'=>array(          'property2'=>'value2',      ),  ),
)


In the above, we differentiate action providers from other action declarations by the array keys. For action providers, the array keys must contain a dot. As a result, an action ID 'pro2.action1' will be resolved as the 'action1' action declared in the 'ProviderClass'.

参见

  • createAction
afterAction() 方法
protected void afterAction(CAction $action)
$actionCActionthe action just executed.
源码: framework/web/CController.php#1104 (显示) protectedfunctionafterAction($action)
{
}

This method is invoked right after an action is executed. You may override this method to do some postprocessing for the action.

afterRender() 方法 (可用自 v1.1.5)
protected void afterRender(string $view, string &$output)
$viewstringthe view that has been rendered
$outputstringthe rendering result of the view. Note that this parameter is passed as a reference. That means you can modify it within this method.
源码: framework/web/CController.php#819 (显示) protectedfunctionafterRender($view,&$output)
{
}

This method is invoked after the specified is rendered by calling render(). Note that this method is invoked BEFORE processOutput(). You may override this method to do some postprocessing for the view rendering.

beforeAction() 方法
protected boolean beforeAction(CAction $action)
$actionCActionthe action to be executed.
{return}booleanwhether the action should be executed.
源码: framework/web/CController.php#1094 (显示) protectedfunctionbeforeAction($action)
{
returntrue;
}

This method is invoked right before an action is to be executed (after all possible filters.) You may override this method to do last-minute preparation for the action.

beforeRender() 方法 (可用自 v1.1.5)
protected boolean beforeRender(string $view)
$viewstringthe view to be rendered
{return}booleanwhether the view should be rendered.
源码: framework/web/CController.php#805 (显示) protectedfunctionbeforeRender($view)
{
returntrue;
}

This method is invoked at the beginning of render(). You may override this method to do some preprocessing when rendering a view.

behaviors() 方法
public array behaviors()
{return}arraythe behavior configurations (behavior name=>behavior configuration)
源码: framework/web/CController.php#234 (显示) publicfunctionbehaviors()
{
returnarray();
}

Returns a list of behaviors that this controller should behave as. The return value should be an array of behavior configurations indexed by behavior names. Each behavior configuration can be either a string specifying the behavior class or an array of the following structure:

'behaviorName'=>array(  'class'=>'path.to.BehaviorClass',  'property1'=>'value1',  'property2'=>'value2',
)


Note, the behavior classes must implement IBehavior or extend from CBehavior. Behaviors declared in this method will be attached to the controller when it is instantiated.

For more details about behaviors, see CComponent.

clearPageStates() 方法
public void clearPageStates()
源码: framework/web/CController.php#1195 (显示) publicfunctionclearPageStates()
{
$this->_pageStates=array();
}

Removes all page states.

createAbsoluteUrl() 方法
public string createAbsoluteUrl(string $route, array $params=array ( ), string $schema='', string $ampersand='&')
$routestringthe URL route. This should be in the format of 'ControllerID/ActionID'. If the ControllerPath is not present, the current controller ID will be prefixed to the route. If the route is empty, it is assumed to be the current action.
$paramsarrayadditional GET parameters (name=>value). Both the name and value will be URL-encoded.
$schemastringschema to use (e.g. http, https). If empty, the schema used for the current request will be used.
$ampersandstringthe token separating name-value pairs in the URL.
{return}stringthe constructed URL
源码: framework/web/CController.php#981 (显示) publicfunctioncreateAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
{
$url=$this->createUrl($route,$params,$ampersand);
if(strpos($url,'http')===0)
return$url;
else
returnYii::app()->getRequest()->getHostInfo($schema).$url;
}

Creates an absolute URL for the specified action defined in this controller.

createAction() 方法
public CAction createAction(string $actionID)
$actionIDstringID of the action. If empty, the default action will be used.
{return}CActionthe action instance, null if the action does not exist.
源码: framework/web/CController.php#410 (显示) publicfunctioncreateAction($actionID)
{
if($actionID==='')
$actionID=$this->defaultAction;
if(method_exists($this,'action'.$actionID)&&strcasecmp($actionID,'s'))//wehaveactionsmethod
returnnewCInlineAction($this,$actionID);
else
{
$action=$this->createActionFromMap($this->actions(),$actionID,$actionID);
if($action!==null&&!method_exists($action,'run'))
thrownewCException(Yii::t('yii','Actionclass{class}mustimplementthe"run"method.',array('{class}'=>get_class($action))));
return$action;
}
}

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 actions.

参见

  • actions
createActionFromMap() 方法
protected CAction createActionFromMap(array $actionMap, string $actionID, string $requestActionID, array $config=array ( ))
$actionMaparraythe action map
$actionIDstringthe action ID that has its prefix stripped off
$requestActionIDstringthe originally requested action ID
$configarraythe action configuration that should be applied on top of the configuration specified in the map
{return}CActionthe action instance, null if the action does not exist.
源码: framework/web/CController.php#436 (显示) protectedfunctioncreateActionFromMap($actionMap,$actionID,$requestActionID,$config=array())
{
if(($pos=strpos($actionID,'.'))===false&&isset($actionMap[$actionID]))
{
$baseConfig=is_array($actionMap[$actionID])?$actionMap[$actionID]:array('class'=>$actionMap[$actionID]);
returnYii::createComponent(empty($config)?$baseConfig:array_merge($baseConfig,$config),$this,$requestActionID);
}
elseif($pos===false)
returnnull;

//theactionisdefinedinaprovider
$prefix=substr($actionID,0,$pos+1);
if(!isset($actionMap[$prefix]))
returnnull;
$actionID=(string)substr($actionID,$pos+1);

$provider=$actionMap[$prefix];
if(is_string($provider))
$providerType=$provider;
elseif(is_array($provider)&&isset($provider['class']))
{
$providerType=$provider['class'];
if(isset($provider[$actionID]))
{
if(is_string($provider[$actionID]))
$config=array_merge(array('class'=>$provider[$actionID]),$config);
else
$config=array_merge($provider[$actionID],$config);
}
}
else
thrownewCException(Yii::t('yii','Objectconfigurationmustbeanarraycontaininga"class"element.'));

$class=Yii::import($providerType,true);
$map=call_user_func(array($class,'actions'));

return$this->createActionFromMap($map,$actionID,$requestActionID,$config);
}

Creates the action instance based on the action map. This method will check to see if the action ID appears in the given action map. If so, the corresponding configuration will be used to create the action instance.

createUrl() 方法
public string createUrl(string $route, array $params=array ( ), string $ampersand='&')
$routestringthe URL route. This should be in the format of 'ControllerID/ActionID'. If the ControllerID is not present, the current controller ID will be prefixed to the route. If the route is empty, it is assumed to be the current action. If the controller belongs to a module, the module ID will be prefixed to the route. (If you do not want the module ID prefix, the route should start with a slash '/'.)
$paramsarrayadditional GET parameters (name=>value). Both the name and value will be URL-encoded. If the name is '#', the corresponding value will be treated as an anchor and will be appended at the end of the URL.
$ampersandstringthe token separating name-value pairs in the URL.
{return}stringthe constructed URL
源码: framework/web/CController.php#960 (显示) publicfunctioncreateUrl($route,$params=array(),$ampersand='&')
{
if($route==='')
$route=$this->getId().'/'.$this->getAction()->getId();
elseif(strpos($route,'/')===false)
$route=$this->getId().'/'.$route;
if($route[0]!=='/'&&($module=$this->getModule())!==null)
$route=$module->getId().'/'.$route;
returnYii::app()->createUrl(trim($route,'/'),$params,$ampersand);
}

Creates a relative URL for the specified action defined in this controller.

filterAccessControl() 方法
public void filterAccessControl(CFilterChain $filterChain)
$filterChainCFilterChainthe filter chain that the filter is on.
源码: framework/web/CController.php#1142 (显示) publicfunctionfilterAccessControl($filterChain)
{
$filter=newCAccessControlFilter;
$filter->setRules($this->accessRules());
$filter->filter($filterChain);
}

The filter method for 'accessControl' filter. This filter is a wrapper of CAccessControlFilter. To use this filter, you must override accessRules method.

filterAjaxOnly() 方法
public void filterAjaxOnly(CFilterChain $filterChain)
$filterChainCFilterChainthe filter chain that the filter is on.
源码: framework/web/CController.php#1128 (显示) publicfunctionfilterAjaxOnly($filterChain)
{
if(Yii::app()->getRequest()->getIsAjaxRequest())
$filterChain->run();
else
thrownewCHttpException(400,Yii::t('yii','Yourrequestisinvalid.'));
}

The filter method for 'ajaxOnly' filter. This filter reports an error if the applied action is receiving a non-AJAX request.

filterPostOnly() 方法
public void filterPostOnly(CFilterChain $filterChain)
$filterChainCFilterChainthe filter chain that the filter is on.
源码: framework/web/CController.php#1114 (显示) publicfunctionfilterPostOnly($filterChain)
{
if(Yii::app()->getRequest()->getIsPostRequest())
$filterChain->run();
else
thrownewCHttpException(400,Yii::t('yii','Yourrequestisinvalid.'));
}

The filter method for 'postOnly' filter. This filter reports an error if the applied action is receiving a non-POST request.

filters() 方法
public array filters()
{return}arraya list of filter configurations.
源码: framework/web/CController.php#154 (显示) publicfunctionfilters()
{
returnarray();
}

Returns the filter configurations.

By overriding this method, child classes can specify filters to be applied to actions.

This method returns an array of filter specifications. Each array element specify a single filter.

For a method-based filter (called inline filter), it is specified as 'FilterName[ +|- Action1, Action2, ...]', where the '+' ('-') operators describe which actions should be (should not be) applied with the filter.

For a class-based filter, it is specified as an array like the following:

array(  'FilterClass[ +|- Action1, Action2, ...]',  'name1'=>'value1',  'name2'=>'value2',  ...
)
where the name-value pairs will be used to initialize the properties of the filter.

Note, in order to inherit filters defined in the parent class, a child class needs to merge the parent filters with child filters using functions like array_merge().

参见

  • CFilter
forward() 方法 (可用自 v1.1.0)
public void forward(string $route, boolean $exit=true)
$routestringthe route of the new controller action. This can be an action ID, or a complete route with module ID (optional in the current module), controller ID and action ID. If the former, the action is assumed to be located within the current controller.
$exitbooleanwhether to end the application after this call. Defaults to true.
源码: framework/web/CController.php#745 (显示) publicfunctionforward($route,$exit=true)
{
if(strpos($route,'/')===false)
$this->run($route);
else
{
if($route[0]!=='/'&&($module=$this->getModule())!==null)
$route=$module->getId().'/'.$route;
Yii::app()->runController($route);
}
if($exit)
Yii::app()->end();
}

Processes the request using another controller action. This is like redirect, but the user browser's URL remains unchanged. In most cases, you should call redirect instead of this method.

getAction() 方法
public CAction getAction()
{return}CActionthe action currently being executed, null if no active action.
源码: framework/web/CController.php#491 (显示) publicfunctiongetAction()
{
return$this->_action;
}
getActionParams() 方法 (可用自 v1.1.7)
public array getActionParams()
{return}arraythe request parameters to be used for action parameter binding
源码: framework/web/CController.php#324 (显示) publicfunctiongetActionParams()
{
return$_GET;
}

Returns the request parameters that will be used for action parameter binding. By default, this method will return $_GET. You may override this method if you want to use other request parameters (e.g. $_GET+$_POST).

getCachingStack() 方法
public CStack getCachingStack(boolean $createIfNull=true)
$createIfNullbooleanwhether to create a stack if it does not exist yet. Defaults to true.
{return}CStackstack of COutputCache objects
源码: framework/web/CController.php#1070 (显示) publicfunctiongetCachingStack($createIfNull=true)
{
if(!$this->_cachingStack)
$this->_cachingStack=newCStack;
return$this->_cachingStack;
}
getClips() 方法
public CMap getClips()
{return}CMapthe list of clips
源码: framework/web/CController.php#727 (显示) publicfunctiongetClips()
{
if($this->_clips!==null)
return$this->_clips;
else
return$this->_clips=newCMap;
}

Returns the list of clips. A clip is a named piece of rendering result that can be inserted at different places.

参见

  • CClipWidget
getId() 方法
public string getId()
{return}stringID of the controller
源码: framework/web/CController.php#507 (显示) publicfunctiongetId()
{
return$this->_id;
}
getLayoutFile() 方法
public string getLayoutFile(mixed $layoutName)
$layoutNamemixedlayout name
{return}stringthe view file for the layout. False if the view file cannot be found
源码: framework/web/CController.php#634 (显示) publicfunctiongetLayoutFile($layoutName)
{
if($layoutName===false)
returnfalse;
if(($theme=Yii::app()->getTheme())!==null&&($layoutFile=$theme->getLayoutFile($this,$layoutName))!==false)
return$layoutFile;

if(empty($layoutName))
{
$module=$this->getModule();
while($module!==null)
{
if($module->layout===false)
returnfalse;
if(!empty($module->layout))
break;
$module=$module->getParentModule();
}
if($module===null)
$module=Yii::app();
$layoutName=$module->layout;
}
elseif(($module=$this->getModule())===null)
$module=Yii::app();

return$this->resolveViewFile($layoutName,$module->getLayoutPath(),Yii::app()->getViewPath(),$module->getViewPath());
}

Looks for the layout view script based on the layout name.

The layout name can be specified in one of the following ways:

  • layout is false: returns false, meaning no layout.
  • layout is null: the currently active module's layout will be used. If there is no active module, the application's layout will be used.
  • a regular view name.


The resolution of the view file based on the layout view is similar to that in getViewFile. In particular, the following rules are followed:

Otherwise, this method will return the corresponding view file based on the following criteria:
  • When a theme is currently active, this method will call CTheme::getLayoutFile to determine which view file should be returned.
  • absolute view within a module: the view name starts with a single slash '/'. In this case, the view will be searched for under the currently active module's view path. If there is no active module, the view will be searched for under the application's view path.
  • absolute view within the application: the view name starts with double slashes '//'. In this case, the view will be searched for under the application's view path. This syntax has been available since version 1.1.3.
  • aliased view: the view name contains dots and refers to a path alias. The view file is determined by calling YiiBase::getPathOfAlias(). Note that aliased views cannot be themed because they can refer to a view file located at arbitrary places.
  • relative view: otherwise. Relative views will be searched for under the currently active module's layout path. In case when there is no active module, the view will be searched for under the application's layout path.


After the view file is identified, this method may further call CApplication::findLocalizedFile to find its localized version if internationalization is needed.

getModule() 方法
public CWebModule getModule()
{return}CWebModulethe module that this controller belongs to. It returns null if the controller does not belong to any module
源码: framework/web/CController.php#536 (显示) publicfunctiongetModule()
{
return$this->_module;
}
getPageState() 方法
public mixed getPageState(string $name, mixed $defaultValue=NULL)
$namestringthe state name
$defaultValuemixedthe value to be returned if the named state is not found
{return}mixedthe page state value
源码: framework/web/CController.php#1160 (显示) publicfunctiongetPageState($name,$defaultValue=null)
{
if($this->_pageStates===null)
$this->_pageStates=$this->loadPageStates();
returnisset($this->_pageStates[$name])?$this->_pageStates[$name]:$defaultValue;
}

Returns a persistent page state value. A page state is a variable that is persistent across POST requests of the same page. In order to use persistent page states, the form(s) must be stateful which are generated using CHtml::statefulForm.

参见

  • setPageState
  • CHtml::statefulForm
getPageTitle() 方法
public string getPageTitle()
{return}stringthe page title. Defaults to the controller name and the action name.
源码: framework/web/CController.php#993 (显示) publicfunctiongetPageTitle()
{
if($this->_pageTitle!==null)
return$this->_pageTitle;
else
{
$name=ucfirst(basename($this->getId()));
if($this->getAction()!==null&&strcasecmp($this->getAction()->getId(),$this->defaultAction))
return$this->_pageTitle=Yii::app()->name.'-'.ucfirst($this->getAction()->getId()).''.$name;
else
return$this->_pageTitle=Yii::app()->name.'-'.$name;
}
}
getRoute() 方法 (可用自 v1.1.0)
public string getRoute()
{return}stringthe route (module ID, controller ID and action ID) of the current request.
源码: framework/web/CController.php#524 (显示) publicfunctiongetRoute()
{
if(($action=$this->getAction())!==null)
return$this->getUniqueId().'/'.$action->getId();
else
return$this->getUniqueId();
}
getUniqueId() 方法
public string getUniqueId()
{return}stringthe controller ID that is prefixed with the module ID (if any).
源码: framework/web/CController.php#515 (显示) publicfunctiongetUniqueId()
{
return$this->_module?$this->_module->getId().'/'.$this->_id:$this->_id;
}
getViewFile() 方法
public string getViewFile(string $viewName)
$viewNamestringview name
{return}stringthe view file path, false if the view file does not exist
源码: framework/web/CController.php#585 (显示) publicfunctiongetViewFile($viewName)
{
if(($theme=Yii::app()->getTheme())!==null&&($viewFile=$theme->getViewFile($this,$viewName))!==false)
return$viewFile;
$moduleViewPath=$basePath=Yii::app()->getViewPath();
if(($module=$this->getModule())!==null)
$moduleViewPath=$module->getViewPath();
return$this->resolveViewFile($viewName,$this->getViewPath(),$basePath,$moduleViewPath);
}

Looks for the view file according to the given view name.

When a theme is currently active, this method will call CTheme::getViewFile to determine which view file should be returned.

Otherwise, this method will return the corresponding view file based on the following criteria:

  • absolute view within a module: the view name starts with a single slash '/'. In this case, the view will be searched for under the currently active module's view path. If there is no active module, the view will be searched for under the application's view path.
  • absolute view within the application: the view name starts with double slashes '//'. In this case, the view will be searched for under the application's view path. This syntax has been available since version 1.1.3.
  • aliased view: the view name contains dots and refers to a path alias. The view file is determined by calling YiiBase::getPathOfAlias(). Note that aliased views cannot be themed because they can refer to a view file located at arbitrary places.
  • relative view: otherwise. Relative views will be searched for under the currently active controller's view path.


After the view file is identified, this method may further call CApplication::findLocalizedFile to find its localized version if internationalization is needed.

参见

  • resolveViewFile
  • CApplication::findLocalizedFile
getViewPath() 方法
public string getViewPath()
{return}stringthe directory containing the view files for this controller. Defaults to 'protected/views/ControllerID'.
源码: framework/web/CController.php#549 (显示) publicfunctiongetViewPath()
{
if(($module=$this->getModule())===null)
$module=Yii::app();
return$module->getViewPath().DIRECTORY_SEPARATOR.$this->getId();
}

Returns the directory containing view files for this controller. The default implementation returns 'protected/views/ControllerID'. Child classes may override this method to use customized view path. If the controller belongs to a module, the default view path is the module view path appended with the controller ID.

init() 方法
public void init()
源码: framework/web/CController.php#123 (显示) publicfunctioninit()
{
}

Initializes the controller. This method is called by the application before the controller starts to execute. You may override this method to perform the needed initialization for the controller.

invalidActionParams() 方法 (可用自 v1.1.7)
public void invalidActionParams(CAction $action)
$actionCActionthe action being executed
源码: framework/web/CController.php#335 (显示) publicfunctioninvalidActionParams($action)
{
thrownewCHttpException(400,Yii::t('yii','Yourrequestisinvalid.'));
}

This method is invoked when the request parameters do not satisfy the requirement of the specified action. The default implementation will throw a 400 HTTP exception.

isCachingStackEmpty() 方法
public boolean isCachingStackEmpty()
{return}booleanwhether the caching stack is empty. If not empty, it means currently there are some output cache in effect. Note, the return result of this method may change when it is called in different output regions, depending on the partition of output caches.
源码: framework/web/CController.php#1083 (显示) publicfunctionisCachingStackEmpty()
{
return$this->_cachingStack===null||!$this->_cachingStack->getCount();
}

Returns whether the caching stack is empty.

loadPageStates() 方法
protected array loadPageStates()
{return}arraythe loaded page states
源码: framework/web/CController.php#1204 (显示) protectedfunctionloadPageStates()
{
if(!empty($_POST[self::STATE_INPUT_NAME]))
{
if(($data=base64_decode($_POST[self::STATE_INPUT_NAME]))!==false)
{
if(extension_loaded('zlib'))
$data=@gzuncompress($data);
if(($data=Yii::app()->getSecurityManager()->validateData($data))!==false)
returnunserialize($data);
}
}
returnarray();
}

Loads page states from a hidden input.

missingAction() 方法
public void missingAction(string $actionID)
$actionIDstringthe missing action name
源码: framework/web/CController.php#482 (显示) publicfunctionmissingAction($actionID)
{
thrownewCHttpException(404,Yii::t('yii','Thesystemisunabletofindtherequestedaction"{action}".',
array('{action}'=>$actionID==''?$this->defaultAction:$actionID)));
}

Handles the request whose action is not recognized. This method is invoked when the controller cannot find the requested action. The default implementation simply throws an exception.

processDynamicOutput() 方法
public string processDynamicOutput(string $output)
$outputstringoutput to be processed
{return}stringthe processed output
源码: framework/web/CController.php#375 (显示) publicfunctionprocessDynamicOutput($output)
{
if($this->_dynamicOutput)
{
$output=preg_replace_callback('/<###dynamic-(d+)###>/',array($this,'replaceDynamicOutput'),$output);
}
return$output;
}

Postprocesses the dynamic output. This method is internally used. Do not call this method directly.

processOutput() 方法
public string processOutput(string $output)
$outputstringthe output generated by the current action
{return}stringthe output that has been processed.
源码: framework/web/CController.php#350 (显示) publicfunctionprocessOutput($output)
{
Yii::app()->getClientScript()->render($output);

//ifusingpagecaching,weshoulddelaydynamicoutputreplacement
if($this->_dynamicOutput!==null&&$this->isCachingStackEmpty())
{
$output=$this->processDynamicOutput($output);
$this->_dynamicOutput=null;
}

if($this->_pageStates===null)
$this->_pageStates=$this->loadPageStates();
if(!empty($this->_pageStates))
$this->savePageStates($this->_pageStates,$output);

return$output;
}

Postprocesses the output generated by render(). This method is invoked at the end of render() and renderText(). If there are registered client scripts, this method will insert them into the output at appropriate places. If there are dynamic contents, they will also be inserted. This method may also save the persistent page states in hidden fields of stateful forms in the page.

recordCachingAction() 方法
public void recordCachingAction(string $context, string $method, array $params)
$contextstringa property name of the controller. It refers to an object whose method is being called. If empty it means the controller itself.
$methodstringthe method name
$paramsarrayparameters passed to the method
源码: framework/web/CController.php#1057 (显示) publicfunctionrecordCachingAction($context,$method,$params)
{
if($this->_cachingStack)//recordonlywhenthereisanactiveoutputcache
{
foreach($this->_cachingStackas$cache)
$cache->recordAction($context,$method,$params);
}
}

Records a method call when an output cache is in effect. When the content is served from the output cache, the recorded method will be re-invoked.

参见

  • COutputCache
redirect() 方法
public void redirect(mixed $url, boolean $terminate=true, integer $statusCode=302)
$urlmixedthe URL to be redirected to. If the parameter is an array, the first element must be a route to a controller action and the rest are GET parameters in name-value pairs.
$terminatebooleanwhether to terminate the current application after calling this method
$statusCodeintegerthe HTTP status code. Defaults to 302. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for details about HTTP status code.
源码: framework/web/CController.php#1024 (显示) publicfunctionredirect($url,$terminate=true,$statusCode=302)
{
if(is_array($url))
{
$route=isset($url[0])?$url[0]:'';
$url=$this->createUrl($route,array_splice($url,1));
}
Yii::app()->getRequest()->redirect($url,$terminate,$statusCode);
}

Redirects the browser to the specified URL or route (controller/action).

refresh() 方法
public void refresh(boolean $terminate=true, string $anchor='')
$terminatebooleanwhether to terminate the current application after calling this method
$anchorstringthe anchor that should be appended to the redirection URL. Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.
源码: framework/web/CController.php#1042 (显示) publicfunctionrefresh($terminate=true,$anchor='')
{
$this->redirect(Yii::app()->getRequest()->getUrl().$anchor,$terminate);
}

Refreshes the current page. The effect of this method call is the same as user pressing the refresh button on the browser (without post data).

render() 方法
public string render(string $view, array $data=NULL, boolean $return=false)
$viewstringname of the view to be rendered. See getViewFile for details about how the view script is resolved.
$dataarraydata to be extracted into PHP variables and made available to the view script
$returnbooleanwhether the rendering result should be returned instead of being displayed to end users.
{return}stringthe rendering result. Null if the rendering result is not required.
源码: framework/web/CController.php#779 (显示) publicfunctionrender($view,$data=null,$return=false)
{
if($this->beforeRender($view))
{
$output=$this->renderPartial($view,$data,true);
if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
$output=$this->renderFile($layoutFile,array('content'=>$output),true);

$this->afterRender($view,$output);

$output=$this->processOutput($output);

if($return)
return$output;
else
echo$output;
}
}

Renders a view with a layout.

This method first calls renderPartial to render the view (called content view). It then renders the layout view which may embed the content view at appropriate place. In the layout view, the content view rendering result can be accessed via variable $content. At the end, it calls processOutput to insert scripts and dynamic contents if they are available.

By default, the layout view script is "protected/views/layouts/main.php". This may be customized by changing layout.

参见

  • renderPartial
  • getLayoutFile
renderClip() 方法 (可用自 v1.1.8)
public mixed renderClip(string $name, array $params=array ( ), boolean $return=false)
$namestringthe name of the clip
$paramsarrayan array of named parameters (name=>value) that should replace their corresponding placeholders in the clip
$returnbooleanwhether to return the clip content or echo it.
{return}mixedeither the clip content or null
源码: framework/web/CController.php#895 (显示) publicfunctionrenderClip($name,$params=array(),$return=false)
{
$text=isset($this->clips[$name])?strtr($this->clips[$name],$params):'';

if($return)
return$text;
else
echo$text;
}

Renders a named clip with the supplied parameters. This is similar to directly accessing the clips property. The main difference is that it can take an array of named parameters which will replace the corresponding placeholders in the clip.

renderDynamic() 方法
public void renderDynamic(callback $callback)
$callbackcallbacka PHP callback which returns the needed dynamic content. When the callback is specified as a string, it will be first assumed to be a method of the current controller class. If the method does not exist, it is assumed to be a global PHP function. Note, the callback should return the dynamic content instead of echoing it.
源码: framework/web/CController.php#924 (显示) publicfunctionrenderDynamic($callback)
{
$n=count($this->_dynamicOutput);
echo"<###dynamic-$n###>";
$params=func_get_args();
array_shift($params);
$this->renderDynamicInternal($callback,$params);
}

Renders dynamic content returned by the specified callback. This method is used together with COutputCache. Dynamic contents will always show as their latest state even if the content surrounding them is being cached. This is especially useful when caching pages that are mostly static but contain some small dynamic regions, such as username or current time. We can use this method to render these dynamic regions to ensure they are always up-to-date.

The first parameter to this method should be a valid PHP callback, while the rest parameters will be passed to the callback.

Note, the callback and its parameter values will be serialized and saved in cache. Make sure they are serializable.

renderDynamicInternal() 方法
public void renderDynamicInternal(callback $callback, array $params)
$callbackcallbacka PHP callback which returns the needed dynamic content.
$paramsarrayparameters passed to the PHP callback
源码: framework/web/CController.php#939 (显示) publicfunctionrenderDynamicInternal($callback,$params)
{
$this->recordCachingAction('','renderDynamicInternal',array($callback,$params));
if(is_string($callback)&&method_exists($this,$callback))
$callback=array($this,$callback);
$this->_dynamicOutput[]=call_user_func_array($callback,$params);
}

This method is internally used.

参见

  • renderDynamic
renderPartial() 方法
public string renderPartial(string $view, array $data=NULL, boolean $return=false, boolean $processOutput=false)
$viewstringname of the view to be rendered. See getViewFile for details about how the view script is resolved.
$dataarraydata to be extracted into PHP variables and made available to the view script
$returnbooleanwhether the rendering result should be returned instead of being displayed to end users
$processOutputbooleanwhether the rendering result should be postprocessed using processOutput.
{return}stringthe rendering result. Null if the rendering result is not required.
源码: framework/web/CController.php#866 (显示) publicfunctionrenderPartial($view,$data=null,$return=false,$processOutput=false)
{
if(($viewFile=$this->getViewFile($view))!==false)
{
$output=$this->renderFile($viewFile,$data,true);
if($processOutput)
$output=$this->processOutput($output);
if($return)
return$output;
else
echo$output;
}
else
thrownewCException(Yii::t('yii','{controller}cannotfindtherequestedview"{view}".',
array('{controller}'=>get_class($this),'{view}'=>$view)));
}

Renders a view.

The named view refers to a PHP script (resolved via getViewFile) that is included by this method. If $data is an associative array, it will be extracted as PHP variables and made available to the script.

This method differs from render() in that it does not apply a layout to the rendered result. It is thus mostly used in rendering a partial view, or an AJAX response.

参见

  • getViewFile
  • processOutput
  • render
renderText() 方法
public string renderText(string $text, boolean $return=false)
$textstringthe static text string
$returnbooleanwhether the rendering result should be returned instead of being displayed to end users.
{return}stringthe rendering result. Null if the rendering result is not required.
源码: framework/web/CController.php#831 (显示) publicfunctionrenderText($text,$return=false)
{
if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
$text=$this->renderFile($layoutFile,array('content'=>$text),true);

$text=$this->processOutput($text);

if($return)
return$text;
else
echo$text;
}

Renders a static text string. The string will be inserted in the current controller layout and returned back.

参见

  • getLayoutFile
replaceDynamicOutput() 方法
protected string replaceDynamicOutput(array $matches)
$matchesarraymatches
{return}stringthe replacement
源码: framework/web/CController.php#391 (显示) protectedfunctionreplaceDynamicOutput($matches)
{
$content=$matches[0];
if(isset($this->_dynamicOutput[$matches[1]]))
{
$content=$this->_dynamicOutput[$matches[1]];
$this->_dynamicOutput[$matches[1]]=null;
}
return$content;
}

Replaces the dynamic content placeholders with actual content. This is a callback function used internally.

参见

  • processOutput
resolveViewFile() 方法
public mixed resolveViewFile(string $viewName, string $viewPath, string $basePath, string $moduleViewPath=NULL)
$viewNamestringthe view name
$viewPathstringthe directory that is used to search for a relative view name
$basePathstringthe directory that is used to search for an absolute view name under the application
$moduleViewPathstringthe directory that is used to search for an absolute view name under the current module. If this is not set, the application base view path will be used.
{return}mixedthe view file path. False if the view file does not exist.
源码: framework/web/CController.php#688 (显示) publicfunctionresolveViewFile($viewName,$viewPath,$basePath,$moduleViewPath=null)
{
if(empty($viewName))
returnfalse;

if($moduleViewPath===null)
$moduleViewPath=$basePath;

if(($renderer=Yii::app()->getViewRenderer())!==null)
$extension=$renderer->fileExtension;
else
$extension='.php';
if($viewName[0]==='/')
{
if(strncmp($viewName,'//',2)===0)
$viewFile=$basePath.$viewName;
else
$viewFile=$moduleViewPath.$viewName;
}
elseif(strpos($viewName,'.'))
$viewFile=Yii::getPathOfAlias($viewName);
else
$viewFile=$viewPath.DIRECTORY_SEPARATOR.$viewName;

if(is_file($viewFile.$extension))
returnYii::app()->findLocalizedFile($viewFile.$extension);
elseif($extension!=='.php'&&is_file($viewFile.'.php'))
returnYii::app()->findLocalizedFile($viewFile.'.php');
else
returnfalse;
}

Finds a view file based on its name. The view name can be in one of the following formats:

  • absolute view within a module: the view name starts with a single slash '/'. In this case, the view will be searched for under the currently active module's view path. If there is no active module, the view will be searched for under the application's view path.
  • absolute view within the application: the view name starts with double slashes '//'. In this case, the view will be searched for under the application's view path. This syntax has been available since version 1.1.3.
  • aliased view: the view name contains dots and refers to a path alias. The view file is determined by calling YiiBase::getPathOfAlias(). Note that aliased views cannot be themed because they can refer to a view file located at arbitrary places.
  • relative view: otherwise. Relative views will be searched for under the currently active controller's view path.
For absolute view and relative view, the corresponding view file is a PHP file whose name is the same as the view name. The file is located under a specified directory. This method will call CApplication::findLocalizedFile to search for a localized file, if any.

run() 方法
public void run(string $actionID)
$actionIDstringaction ID
源码: framework/web/CController.php#258 (显示) publicfunctionrun($actionID)
{
if(($action=$this->createAction($actionID))!==null)
{
if(($parent=$this->getModule())===null)
$parent=Yii::app();
if($parent->beforeControllerAction($this,$action))
{
$this->runActionWithFilters($action,$this->filters());
$parent->afterControllerAction($this,$action);
}
}
else
$this->missingAction($actionID);
}

Runs the named action. Filters specified via filters() will be applied.

参见

  • filters
  • createAction
  • runAction
runAction() 方法
public void runAction(CAction $action)
$actionCActionaction to run
源码: framework/web/CController.php#303 (显示) publicfunctionrunAction($action)
{
$priorAction=$this->_action;
$this->_action=$action;
if($this->beforeAction($action))
{
if($action->runWithParams($this->getActionParams())===false)
$this->invalidActionParams($action);
else
$this->afterAction($action);
}
$this->_action=$priorAction;
}

Runs the action after passing through all filters. This method is invoked by runActionWithFilters after all possible filters have been executed and the action starts to run.

runActionWithFilters() 方法
public void runActionWithFilters(CAction $action, array $filters)
$actionCActionthe action to be executed.
$filtersarraylist of filters to be applied to the action.
源码: framework/web/CController.php#284 (显示) publicfunctionrunActionWithFilters($action,$filters)
{
if(empty($filters))
$this->runAction($action);
else
{
$priorAction=$this->_action;
$this->_action=$action;
CFilterChain::create($this,$action,$filters)->run();
$this->_action=$priorAction;
}
}

Runs an action with the specified filters. A filter chain will be created based on the specified filters and the action will be executed then.

参见

  • filters
  • createAction
  • runAction
savePageStates() 方法
protected void savePageStates(array $states, string &$output)
$statesarraythe states to be saved.
$outputstringthe output to be modified. Note, this is passed by reference.
源码: framework/web/CController.php#1224 (显示) protectedfunctionsavePageStates($states,&$output)
{
$data=Yii::app()->getSecurityManager()->hashData(serialize($states));
if(extension_loaded('zlib'))
$data=gzcompress($data);
$value=base64_encode($data);
$output=str_replace(CHtml::pageStateField(''),CHtml::pageStateField($value),$output);
}

Saves page states as a base64 string.

setAction() 方法
public void setAction(CAction $value)
$valueCActionthe action currently being executed.
源码: framework/web/CController.php#499 (显示) publicfunctionsetAction($value)
{
$this->_action=$value;
}
setPageState() 方法
public void setPageState(string $name, mixed $value, mixed $defaultValue=NULL)
$namestringthe state name
$valuemixedthe page state value
$defaultValuemixedthe default page state value. If this is the same as the given value, the state will be removed from persistent storage.
源码: framework/web/CController.php#1179 (显示) publicfunctionsetPageState($name,$value,$defaultValue=null)
{
if($this->_pageStates===null)
$this->_pageStates=$this->loadPageStates();
if($value===$defaultValue)
unset($this->_pageStates[$name]);
else
$this->_pageStates[$name]=$value;

$params=func_get_args();
$this->recordCachingAction('','setPageState',$params);
}

Saves a persistent page state value. A page state is a variable that is persistent across POST requests of the same page. In order to use persistent page states, the form(s) must be stateful which are generated using CHtml::statefulForm.

参见

  • getPageState
  • CHtml::statefulForm
setPageTitle() 方法
public void setPageTitle(string $value)
$valuestringthe page title.
源码: framework/web/CController.php#1010 (显示) publicfunctionsetPageTitle($value)
{
$this->_pageTitle=$value;
}