Yii2 Bootstrap 3
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

430 lines
16 KiB

13 years ago
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
13 years ago
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
use Yii;
13 years ago
/**
13 years ago
* Controller is the base class for classes containing controller logic.
13 years ago
*
* @property array $actionParams The request parameters (name-value pairs) to be used for action parameter
* binding. This property is read-only.
* @property string $route The route (module ID, controller ID and action ID) of the current request. This
* property is read-only.
* @property string $uniqueId The controller ID that is prefixed with the module ID (if any). This property is
* read-only.
* @property View $view The view object that can be used to render views or view files.
* @property string $viewPath The directory containing the view files for this controller. This property is
* read-only.
*
13 years ago
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Controller extends Component implements ViewContextInterface
13 years ago
{
/**
* @event ActionEvent an event raised right before executing a controller action.
* You may set [[ActionEvent::isValid]] to be false to cancel the action execution.
*/
const EVENT_BEFORE_ACTION = 'beforeAction';
/**
* @event ActionEvent an event raised right after executing a controller action.
*/
const EVENT_AFTER_ACTION = 'afterAction';
/**
* @var string the ID of this controller.
13 years ago
*/
public $id;
/**
* @var Module $module the module that this controller belongs to.
*/
public $module;
/**
12 years ago
* @var string the ID of the action that is used when the action ID is not specified
* in the request. Defaults to 'index'.
13 years ago
*/
public $defaultAction = 'index';
/**
12 years ago
* @var string|boolean the name of the layout to be applied to this controller's views.
* This property mainly affects the behavior of [[render()]].
* Defaults to null, meaning the actual layout value should inherit that from [[module]]'s layout value.
* If false, no layout will be applied.
*/
public $layout;
/**
* @var Action the action that is currently being executed. This property will be set
* by [[run()]] when it is called by [[Application]] to run an action.
*/
public $action;
12 years ago
/**
* @var View the view object that can be used to render views or view files.
*/
private $_view;
12 years ago
/**
* @param string $id the ID of this controller.
12 years ago
* @param Module $module the module that this controller belongs to.
* @param array $config name-value pairs that will be used to initialize the object properties.
12 years ago
*/
public function __construct($id, $module, $config = [])
12 years ago
{
$this->id = $id;
$this->module = $module;
parent::__construct($config);
}
/**
* Declares external actions for the controller.
* This method is meant to be overwritten to declare external actions for the controller.
* It should return an array, with array keys being action IDs, and array values the corresponding
13 years ago
* action class names or action configuration arrays. For example,
*
* ~~~
* return [
* 'action1' => 'app\components\Action1',
* 'action2' => [
* 'class' => 'app\components\Action2',
13 years ago
* 'property1' => 'value1',
* 'property2' => 'value2',
* ],
* ];
13 years ago
* ~~~
*
12 years ago
* [[\Yii::createObject()]] will be used later to create the requested action
13 years ago
* using the configuration provided here.
*/
12 years ago
public function actions()
13 years ago
{
return [];
13 years ago
}
/**
* Runs an action within this controller with the specified action ID and parameters.
* If the action ID is empty, the method will use [[defaultAction]].
* @param string $id the ID of the action to be executed.
13 years ago
* @param array $params the parameters (name-value pairs) to be passed to the action.
* @return mixed the result of the action.
* @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully.
* @see createAction()
13 years ago
*/
public function runAction($id, $params = [])
13 years ago
{
$action = $this->createAction($id);
if ($action !== null) {
Yii::trace("Route to run: " . $action->getUniqueId(), __METHOD__);
12 years ago
if (Yii::$app->requestedAction === null) {
Yii::$app->requestedAction = $action;
}
$oldAction = $this->action;
$this->action = $action;
$result = null;
12 years ago
$event = new ActionEvent($action);
Yii::$app->trigger(Application::EVENT_BEFORE_ACTION, $event);
12 years ago
if ($event->isValid && $this->module->beforeAction($action) && $this->beforeAction($action)) {
$result = $action->runWithParams($params);
$this->afterAction($action, $result);
$this->module->afterAction($action, $result);
12 years ago
$event = new ActionEvent($action);
$event->result = &$result;
Yii::$app->trigger(Application::EVENT_AFTER_ACTION, $event);
13 years ago
}
$this->action = $oldAction;
return $result;
13 years ago
} else {
throw new InvalidRouteException('Unable to resolve the request: ' . $this->getUniqueId() . '/' . $id);
13 years ago
}
}
13 years ago
/**
* Runs a request specified in terms of a route.
* The route can be either an ID of an action within this controller or a complete route consisting
* of module IDs, controller ID and action ID. If the route starts with a slash '/', the parsing of
* the route will start from the application; otherwise, it will start from the parent module of this controller.
* @param string $route the route to be handled, e.g., 'view', 'comment/view', '/admin/comment/view'.
* @param array $params the parameters to be passed to the action.
* @return mixed the result of the action.
* @see runAction()
*/
public function run($route, $params = [])
{
$pos = strpos($route, '/');
if ($pos === false) {
return $this->runAction($route, $params);
} elseif ($pos > 0) {
return $this->module->runAction($route, $params);
} else {
12 years ago
return Yii::$app->runAction(ltrim($route, '/'), $params);
}
}
13 years ago
/**
12 years ago
* Binds the parameters to the action.
* This method is invoked by [[Action]] when it begins to run with the given parameters.
* @param Action $action the action to be bound with parameters.
* @param array $params the parameters to be bound to the action.
12 years ago
* @return array the valid parameters that the action can run with.
*/
public function bindActionParams($action, $params)
{
return [];
12 years ago
}
/**
* Creates an action based on the given action ID.
* The method first checks if the action ID has been declared in [[actions()]]. If so,
* it will use the configuration declared there to create the action object.
* If not, it will look for a controller method whose name is in the format of `actionXyz`
* where `Xyz` stands for the action ID. If found, an [[InlineAction]] representing that
* method will be created and returned.
* @param string $id the action ID.
* @return Action the newly created action instance. Null if the ID doesn't resolve into any action.
13 years ago
*/
public function createAction($id)
13 years ago
{
12 years ago
if ($id === '') {
$id = $this->defaultAction;
}
$actionMap = $this->actions();
if (isset($actionMap[$id])) {
return Yii::createObject($actionMap[$id], $id, $this);
} elseif (preg_match('/^[a-z0-9\\-_]+$/', $id) && strpos($id, '--') === false && trim($id, '-') === $id) {
$methodName = 'action' . str_replace(' ', '', ucwords(implode(' ', explode('-', $id))));
if (method_exists($this, $methodName)) {
$method = new \ReflectionMethod($this, $methodName);
if ($method->getName() === $methodName) {
12 years ago
return new InlineAction($id, $this, $methodName);
}
}
13 years ago
}
return null;
}
/**
* 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.
* If you override this method, please make sure you call the parent implementation first.
* @param Action $action the action to be executed.
* @return boolean whether the action should continue to be executed.
*/
public function beforeAction($action)
{
$event = new ActionEvent($action);
$this->trigger(self::EVENT_BEFORE_ACTION, $event);
return $event->isValid;
}
/**
* This method is invoked right after an action is executed.
* You may override this method to do some postprocessing for the action.
* If you override this method, please make sure you call the parent implementation first.
* @param Action $action the action just executed.
* @param mixed $result the action return result.
*/
public function afterAction($action, &$result)
{
$event = new ActionEvent($action);
$event->result = &$result;
$this->trigger(self::EVENT_AFTER_ACTION, $event);
13 years ago
}
/**
* Returns the request parameters that will be used for action parameter binding.
* Default implementation simply returns an empty array.
* Child classes may override this method to customize the parameters to be provided
* for action parameter binding (e.g. `$_GET`).
* @return array the request parameters (name-value pairs) to be used for action parameter binding.
13 years ago
*/
public function getActionParams()
{
return [];
13 years ago
}
/**
* @return string the controller ID that is prefixed with the module ID (if any).
*/
public function getUniqueId()
{
13 years ago
return $this->module instanceof Application ? $this->id : $this->module->getUniqueId() . '/' . $this->id;
13 years ago
}
/**
13 years ago
* Returns the route of the current request.
13 years ago
* @return string the route (module ID, controller ID and action ID) of the current request.
*/
public function getRoute()
{
return $this->action !== null ? $this->action->getUniqueId() : $this->getUniqueId();
13 years ago
}
12 years ago
/**
* Renders a view and applies layout if available.
12 years ago
*
* The view to be rendered can be specified in one of the following formats:
*
* - path alias (e.g. "@app/views/site/index");
* - absolute path within application (e.g. "//site/index"): the view name starts with double slashes.
* The actual view file will be looked for under the [[Application::viewPath|view path]] of the application.
* - absolute path within module (e.g. "/site/index"): the view name starts with a single slash.
* The actual view file will be looked for under the [[Module::viewPath|view path]] of [[module]].
* - relative path (e.g. "index"): the actual view file will be looked for under [[viewPath]].
*
* To determine which layout should be applied, the following two steps are conducted:
*
* 1. In the first step, it determines the layout name and the context module:
*
* - If [[layout]] is specified as a string, use it as the layout name and [[module]] as the context module;
* - If [[layout]] is null, search through all ancestor modules of this controller and find the first
* module whose [[Module::layout|layout]] is not null. The layout and the corresponding module
* are used as the layout name and the context module, respectively. If such a module is not found
* or the corresponding layout is not a string, it will return false, meaning no applicable layout.
*
* 2. In the second step, it determines the actual layout file according to the previously found layout name
* and context module. The layout name can be:
12 years ago
*
* - a path alias (e.g. "@app/views/layouts/main");
* - an absolute path (e.g. "/main"): the layout name starts with a slash. The actual layout file will be
* looked for under the [[Application::layoutPath|layout path]] of the application;
* - a relative path (e.g. "main"): the actual layout layout file will be looked for under the
11 years ago
* [[Module::layoutPath|layout path]] of the context module.
12 years ago
*
* If the layout name does not contain a file extension, it will use the default one `.php`.
*
12 years ago
* @param string $view the view name. Please refer to [[findViewFile()]] on how to specify a view name.
* @param array $params the parameters (name-value pairs) that should be made available in the view.
* These parameters will not be available in the layout.
* @return string the rendering result.
* @throws InvalidParamException if the view file or the layout file does not exist.
12 years ago
*/
public function render($view, $params = [])
13 years ago
{
$output = $this->getView()->render($view, $params, $this);
$layoutFile = $this->findLayoutFile($this->getView());
12 years ago
if ($layoutFile !== false) {
return $this->getView()->renderFile($layoutFile, ['content' => $output], $this);
12 years ago
} else {
return $output;
}
13 years ago
}
12 years ago
/**
* Renders a view.
* This method differs from [[render()]] in that it does not apply any layout.
12 years ago
* @param string $view the view name. Please refer to [[render()]] on how to specify a view name.
12 years ago
* @param array $params the parameters (name-value pairs) that should be made available in the view.
* @return string the rendering result.
* @throws InvalidParamException if the view file does not exist.
*/
public function renderPartial($view, $params = [])
13 years ago
{
return $this->getView()->render($view, $params, $this);
13 years ago
}
12 years ago
/**
* Renders a view file.
* @param string $file the view file to be rendered. This can be either a file path or a path alias.
* @param array $params the parameters (name-value pairs) that should be made available in the view.
* @return string the rendering result.
* @throws InvalidParamException if the view file does not exist.
*/
public function renderFile($file, $params = [])
{
12 years ago
return $this->getView()->renderFile($file, $params, $this);
}
/**
* Returns the view object that can be used to render views or view files.
* The [[render()]], [[renderPartial()]] and [[renderFile()]] methods will use
* this view object to implement the actual view rendering.
* If not set, it will default to the "view" application component.
12 years ago
* @return View the view object that can be used to render views or view files.
*/
public function getView()
{
if ($this->_view === null) {
$this->_view = Yii::$app->getView();
}
return $this->_view;
}
/**
* Sets the view object to be used by this controller.
* @param View $view the view object that can be used to render views or view files.
*/
public function setView($view)
{
$this->_view = $view;
13 years ago
}
12 years ago
/**
* Returns the directory containing view files for this controller.
* The default implementation returns the directory named as controller [[id]] under the [[module]]'s
* [[viewPath]] directory.
* @return string the directory containing the view files for this controller.
*/
public function getViewPath()
{
return $this->module->getViewPath() . DIRECTORY_SEPARATOR . $this->id;
}
12 years ago
/**
12 years ago
* Finds the view file based on the given view name.
* @param string $view the view name or the path alias of the view file. Please refer to [[render()]]
* on how to specify this parameter.
* @return string the view file path. Note that the file may not exist.
*/
public function findViewFile($view)
12 years ago
{
return $this->getViewPath() . DIRECTORY_SEPARATOR . $view;
12 years ago
}
/**
12 years ago
* Finds the applicable layout file.
* @param View $view the view object to render the layout file.
12 years ago
* @return string|boolean the layout file path, or false if layout is not needed.
12 years ago
* Please refer to [[render()]] on how to specify this parameter.
* @throws InvalidParamException if an invalid path alias is used to specify the layout.
12 years ago
*/
protected function findLayoutFile($view)
12 years ago
{
12 years ago
$module = $this->module;
12 years ago
if (is_string($this->layout)) {
$layout = $this->layout;
12 years ago
} elseif ($this->layout === null) {
while ($module !== null && $module->layout === null) {
$module = $module->module;
}
if ($module !== null && is_string($module->layout)) {
$layout = $module->layout;
12 years ago
}
}
if (!isset($layout)) {
12 years ago
return false;
}
if (strncmp($layout, '@', 1) === 0) {
$file = Yii::getAlias($layout);
} elseif (strncmp($layout, '/', 1) === 0) {
$file = Yii::$app->getLayoutPath() . DIRECTORY_SEPARATOR . $layout;
12 years ago
} else {
$file = $module->getLayoutPath() . DIRECTORY_SEPARATOR . $layout;
12 years ago
}
if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
return $file;
12 years ago
}
$path = $file . '.' . $view->defaultExtension;
if ($view->defaultExtension !== 'php' && !is_file($path)) {
$path = $file . '.php';
}
return $path;
12 years ago
}
13 years ago
}