原文地址: http://www.cnblogs.com/dragon16/p/5571328.html
Module类是模块和应用类的基类。
yiisoft\yii2\base\Module.php
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
use Yii;
use yii\di\ServiceLocator;
/**
* Module is the base class for module and application classes.
* Module是模块和应用类的基类
* A module represents a sub-application which contains MVC elements by itself, such as
* models, views, controllers, etc.
* 模块是一个由模型、视图、控制器等组成的子应用
* A module may consist of [[modules|sub-modules]].
* 模块内也可以包含模块或子模块
* [[components|Components]] may be registered with the module so that they are globally
* accessible within the module.
* 组件可以注册到模块,以便在模块内全局访问
* @property array $aliases List of path aliases to be defined. The array keys are alias names (must start
* with '@') and the array values are the corresponding paths or aliases. See [[setAliases()]] for an example.
* This property is write-only. 要定义的别名路径数组 只写
* @property string $basePath The root directory of the module. 模块的根路径
* @property string $controllerPath The directory that contains the controller classes. This property is
* read-only. 控制器类的路径 只读
* @property string $layoutPath The root directory of layout files. Defaults to "[[viewPath]]/layouts".
* 模板路径数组 只读
* @property array $modules The modules (indexed by their IDs). 模块数组
* @property string $uniqueId The unique ID of the module. This property is read-only.模块的唯一标识 只读
* @property string $viewPath The root directory of view files. Defaults to "[[basePath]]/views".
* 模块下视图文件路径
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Module extends ServiceLocator
{
/**
* @event ActionEvent an event raised before executing a controller action. 在执行控制的的action方法前触发
* You may set [[ActionEvent::isValid]] to be false to cancel the action execution.
* 可以设置[[ActionEvent::isValid]]为false取消行动的执行。
*/
const EVENT_BEFORE_ACTION = 'beforeAction';
/**
* @event ActionEvent an event raised after executing a controller action.
* 在执行控制的的action方法后触发
*
*/
const EVENT_AFTER_ACTION = 'afterAction';
/**
* @var array custom module parameters (name => value). 自定义模块参数
*/
public $params = [];
/**
* @var string an ID that uniquely identifies this module among other modules which have the same [[module|parent]].
* 模块的唯一标识,用于区分同一父模块下的模块
*/
public $id;
/**
* @var Module the parent module of this module. Null if this module does not have a parent.
* 当前模块的父模块
*/
public $module;
/**
* @var string|boolean the layout that should be applied for views within this module. This refers to a view name
* relative to [[layoutPath]]. If this is not set, it means the layout value of the [[module|parent module]]
* will be taken. If this is false, layout will be disabled within this module.
* 布局文件 如果没有设置,调用 [[module|parent module]]的值。如果是false,在模块中布局将被禁用。
*/
public $layout;
/**
* @var array mapping from controller ID to controller configurations. 控制器ID到控制器配置的映射
* Each name-value pair specifies the configuration of a single controller.
* A controller configuration can be either a string or an array.
* If the former, the string should be the fully qualified class name of the controller.
* If the latter, the array must contain a 'class' element which specifies
* the controller's fully qualified class name, and the rest of the name-value pairs
* in the array are used to initialize the corresponding controller properties. For example,
* 每个键值对指定单独的控制器,控制器配置可以是字符串或者数组,如果是前者,该字符串是指定控制的的全路径
95 * 如果是后者,则包含一个‘class’元素指定控制器的全路径,其余的参数用于初始化对应的属性
* ~~~
* [
* 'account' => 'app\controllers\UserController',
* 'article' => [
* 'class' => 'app\controllers\PostController',
* 'pageTitle' => 'something new',
* ],
* ]
* ~~~
*/
public $controllerMap = [];
/**
* @var string the namespace that controller classes are in. 控制器的命名空间
* This namespace will be used to load controller classes by prepending it to the controller
* class name.
* 命名空间 在控制器类的前面加载控制器类
* If not set, it will use the `controllers` sub-namespace under the namespace of this module.
* For example, if the namespace of this module is "foo\bar", then the default
* controller namespace would be "foo\bar\controllers".
* 如果没有设置,默认为当前模块的命名空间加上 `controllers`构成的命名空间
119 * 如当前模块的命名空间为"foo\bar",控制器的默认命名空间为"foo\bar\controllers"
* See also the [guide section on autoloading](guide:concept-autoloading) to learn more about
* defining namespaces and how classes are loaded.
*/
public $controllerNamespace;
/**
* @var string the default route of this module. Defaults to 'default'. 当前前模块的默认路由
* The route may consist of child module ID, controller ID, and/or action ID.
* For example, `help`, `post/create`, `admin/post/create`.
* If action ID is not given, it will take the default value as specified in
* [[Controller::defaultAction]].
* route 可能包含子模块ID,控制器ID,操作ID,如果action ID未给定,会调用[Controller::defaultAction]指定的action
*/
public $defaultRoute = 'default';
/**
* @var string the root directory of the module. 当前模块的根路径
*/
private $_basePath;
/**
* @var string the root directory that contains view files for this module 当前模块下视图文件的路径
*/
private $_viewPath;
/**
* @var string the root directory that contains layout view files for this module.
* 当前模块下的布局文件路径
*/
private $_layoutPath;
/**
* @var array child modules of this module 当前模块的子模块数组
*/
private $_modules = [];
/**
* Constructor. 构造函数
* @param string $id the ID of this module 当前模块的标识
* @param Module $parent the parent module (if any) 当前模块的父模块
* @param array $config name-value pairs that will be used to initialize the object properties
* 配置文件 用于初始化对象属性
*/
public function __construct($id, $parent = null, $config = [])
{
$this->id = $id; //给当前模块唯一标识
$this->module = $parent; //当前模块的父模块
parent::__construct($config); //调用父类的配置
}
/**
* Returns the currently requested instance of this module class. 取得当前类的实例
* If the module class is not currently requested, null will be returned.
* 没有当前请求的模块类,将返回null。
* This method is provided so that you access the module instance from anywhere within the module.
* 可以在模块内的任何地方访问类的实例
* @return static|null the currently requested instance of this module class, or null if the module class is not requested.
*/
public static function getInstance()
{
$class = get_called_class();
return isset(Yii::$app->loadedModules[$class]) ? Yii::$app->loadedModules[$class] : null;
}
/**
* Sets the currently requested instance of this module class. 设置模块类的当前请求实例。
* @param Module|null $instance the currently requested instance of this module class.
* If it is null, the instance of the calling class will be removed, if any.
* 当前模块类的实例。如果为null,调用类的实例将被删除
*/
public static function setInstance($instance)
{
if ($instance === null) {//如果没有传入参数,直接unset
unset(Yii::$app->loadedModules[get_called_class()]);
} else {//将该类和类的实例存入loadedModules数组中
Yii::$app->loadedModules[get_class($instance)] = $instance;
}
}
/**
* Initializes the module.
* 初始化模块
* This method is called after the module is created and initialized with property values
* given in configuration. The default implementation will initialize [[controllerNamespace]]
* if it is not set.
* 该模块创建和初始化给出的配置 如果没有设置,默认初始化[[controllerNamespace]]
* If you override this method, please make sure you call the parent implementation.
* 重写确保父类调用
*/
public function init()
{
if ($this->controllerNamespace === null) {//判断是否为空
$class = get_class($this); //获取类名
if (($pos = strrpos($class, '\\')) !== false) {
$this->controllerNamespace = substr($class, 0, $pos) . '\\controllers'; //取得命名空间
}
}
}
/**
* Returns an ID that uniquely identifies this module among all modules within the current application.
* Note that if the module is an application, an empty string will be returned.
* 当前应用程序中模块的唯一标识,如果该模块是应用程序返回空字符串
* @return string the unique ID of the module.模块的唯一标识
*/
public function getUniqueId()
{ //如果当前模块有父模块,则返回拼接的标识作为唯一ID,否则只返回当前模块ID
return $this->module ? ltrim($this->module->getUniqueId() . '/' . $this->id, '/') : $this->id;
}
/**
* Returns the root directory of the module. 返回当前模块的根路径
* It defaults to the directory containing the module class file. 默认为包含模块类文件的路径。
* @return string the root directory of the module. 当前模块的根路径
*/
public function getBasePath()
{
if ($this->_basePath === null) {
$class = new \ReflectionClass($this); //生成当前类的反射对象
$this->_basePath = dirname($class->getFileName());//取得类定义的路径
}
return $this->_basePath;
}
/**
* Sets the root directory of the module. 设置当前模块的根路径
* This method can only be invoked at the beginning of the constructor. 只在构造函数开始时调用。
* @param string $path the root directory of the module. This can be either a directory name or a path alias.
* 模块的根目录。可以是一个目录名或路径别名
* @throws InvalidParamException if the directory does not exist. 如果路径不存在。抛出异常
*/
public function setBasePath($path)
{
$path = Yii::getAlias($path);//将路径别名转换为实际路径。
$p = realpath($path); //返回绝对路径名
if ($p !== false && is_dir($p)) {
$this->_basePath = $p;//是目录名且不为false,返回目录名,否则抛出异常
} else {
throw new InvalidParamException("The directory does not exist: $path");
}
}
/**
* Returns the directory that contains the controller classes according to [[controllerNamespace]].
*根据控制器的命名空间返回控制器的目录路径
* Note that in order for this method to return a value, you must define
* an alias for the root namespace of [[controllerNamespace]].
* 为了使该方法返回正确的值,必须为[[controllerNamespace]]定义一个根别名
* @return string the directory that contains the controller classes.
* @throws InvalidParamException if there is no alias defined for the root namespace of [[controllerNamespace]].
*/
public function getControllerPath()
{
//通过将命名空间转换为路径构造别名路径,然后通过getAlias方法取得控制器的绝对路径
return Yii::getAlias('@' . str_replace('\\', '/', $this->controllerNamespace));
}
/**
* Returns the directory that contains the view files for this module.
* 取得当前模块的视图文件目录路径
* @return string the root directory of view files. Defaults to "[[basePath]]/views".
*/
public function getViewPath()
{
if ($this->_viewPath !== null) {
return $this->_viewPath;
} else {
//getBasePath()返回当前模块的根路径,然后拼接出视图文件路径
return $this->_viewPath = $this->getBasePath() . DIRECTORY_SEPARATOR . 'views';
}
}
/**
* Sets the directory that contains the view files.设置视图文件目录路径
* @param string $path the root directory of view files.
* @throws InvalidParamException if the directory is invalid
*/
public function setViewPath($path)
{
$this->_viewPath = Yii::getAlias($path);
}
/**
* Returns the directory that contains layout view files for this module.
* 取得当前模块的布局文件路径
* @return string the root directory of layout files. Defaults to "[[viewPath]]/layouts".
*/
public function getLayoutPath()
{
if ($this->_layoutPath !== null) {
return $this->_layoutPath;
} else {//getBasePath()返回当前模块的根路径,然后拼接出布局文件目录路径
return $this->_layoutPath = $this->getViewPath() . DIRECTORY_SEPARATOR . 'layouts';
}
}
/**
* Sets the directory that contains the layout files.设置当前模块的布局文件路径
* @param string $path the root directory or path alias of layout files.
* @throws InvalidParamException if the directory is invalid
*/
public function setLayoutPath($path)
{
$this->_layoutPath = Yii::getAlias($path);
}
/**
* Defines path aliases. 定义路径别名
* This method calls [[Yii::setAlias()]] to register the path aliases.
* This method is provided so that you can define path aliases when configuring a module.
* 通过调用[[Yii::setAlias()]]注册路径别名,方便在配置模块的时候定义路径别名
* @property array list of path aliases to be defined. The array keys are alias names
* (must start with '@') and the array values are the corresponding paths or aliases.
* See [[setAliases()]] for an example.
* @param array $aliases list of path aliases to be defined. The array keys are alias names
* (must start with '@') and the array values are the corresponding paths or aliases.
* For example,
*
* ~~~
* [
* '@models' => '@app/models', // an existing alias
* '@backend' => __DIR__ . '/../backend', // a directory
* ]
* ~~~
*/
public function setAliases($aliases)
{
foreach ($aliases as $name => $alias) {
Yii::setAlias($name, $alias);//调用[[Yii::setAlias()]]路径别名
}
}
/**
* Checks whether the child module of the specified ID exists.
* This method supports checking the existence of both child and grand child modules.
* @param string $id module ID. For grand child modules, use ID path relative to this module (e.g. `admin/content`).
* @return boolean whether the named module exists. Both loaded and unloaded modules
* are considered.
*/
public function hasModule($id)
{
if (($pos = strpos($id, '/')) !== false) {
// sub-module 如果模块ID格式为 `admin/content` 取出当前模块的子模块
$module = $this->getModule(substr($id, 0, $pos));
//如果没有取到,返回false
return $module === null ? false : $module->hasModule(substr($id, $pos + 1));
} else {
//模块ID没有父模块的情况,直接判断_modules数组中是否有值
return isset($this->_modules[$id]);
}
}
/**
* Retrieves the child module of the specified ID.取出指定模块的子模块
* This method supports retrieving both child modules and grand child modules.
* 该方法支持检索子模块和子模块的子模块
* @param string $id module ID (case-sensitive). To retrieve grand child modules,
* use ID path relative to this module (e.g. `admin/content`).
* 检索子模块,使用标识路径相对
* @param boolean $load whether to load the module if it is not yet loaded. 是否加载模块
* @return Module|null the module instance, null if the module does not exist. 不存在删除
* @see hasModule()
*/
public function getModule($id, $load = true)
{
if (($pos = strpos($id, '/')) !== false) {
// sub-module 判断模块id格式是否为 `admin/content` 取子模块
$module = $this->getModule(substr($id, 0, $pos));
return $module === null ? null : $module->getModule(substr($id, $pos + 1), $load);
}
if (isset($this->_modules[$id])) {
if ($this->_modules[$id] instanceof Module) {
return $this->_modules[$id];//如果_modules数组中有该模块,直接返回该模块
} elseif ($load) {//否则,先实例化后返回
Yii::trace("Loading module: $id", __METHOD__);
/* @var $module Module */
$module = Yii::createObject($this->_modules[$id], [$id, $this]);
$module->setInstance($module);
return $this->_modules[$id] = $module;
}
}
//不存在,返回null
return null;
}
/**
* Adds a sub-module to this module. 为当前模块添加子模块
* @param string $id module ID 模块标识
* @param Module|array|null $module the sub-module to be added to this module. This can
* be one of the followings:
*
* - a [[Module]] object
* - a configuration array: when [[getModule()]] is called initially, the array
* will be used to instantiate the sub-module
* - null: the named sub-module will be removed from this module
*/
public function setModule($id, $module)
{
if ($module === null) {
//为空删除
unset($this->_modules[$id]);
} else {//存在则添加
$this->_modules[$id] = $module;
}
}
/**
* Registers sub-modules in the current module.
* 注册子模块到当前模块
* Each sub-module should be specified as a name-value pair, where
* name refers to the ID of the module and value the module or a configuration
* array that can be used to create the module. In the latter case, [[Yii::createObject()]]
* will be used to create the module.
* 子模块以键值对的方式指定,键名为模块ID,键值为模块对象或者用于创建模块对象的配置数组
* If a new sub-module has the same ID as an existing one, the existing one will be overwritten silently.
* 如果标识相同 会覆盖
* The following is an example for registering two sub-modules:
*
* ~~~
* [
* 'comment' => [
* 'class' => 'app\modules\comment\CommentModule',
* 'db' => 'db',
* ],
* 'booking' => ['class' => 'app\modules\booking\BookingModule'],
* ]
* ~~~
*
* @param array $modules modules (id => module configuration or instances)
*/
public function setModules($modules)
{
foreach ($modules as $id => $module) {
$this->_modules[$id] = $module; //注册子模块,覆盖同名模块
}
}
/**
* Runs a controller action specified by a route. 运行路由中指定的控制器方法
* This method parses the specified route and creates the corresponding child module(s), controller and action
* instances. It then calls [[Controller::runAction()]] to run the action with the given parameters.
* If the route is empty, the method will use [[defaultRoute]].
* 解析指定的路由,创建对应的子模块、控制器、方法实例,调用[[Controller::runAction()]]给定的参数运行控制器中的方法
* @param string $route the route that specifies the action. 指定行动的路线。
* @param array $params the parameters to be passed to the action 操作的参数
* @return mixed the result of the action. 操作结果
* @throws InvalidRouteException if the requested route cannot be resolved into an action successfully
*/
public function runAction($route, $params = [])
{
$parts = $this->createController($route); //根据路由创建控制器
if (is_array($parts)) {
/* @var $controller Controller */
list($controller, $actionID) = $parts; //获得$actionId和$controller
$oldController = Yii::$app->controller;
Yii::$app->controller = $controller;
$result = $controller->runAction($actionID, $params); //运行控制器 加载action方法
Yii::$app->controller = $oldController;
return $result;
} else {
$id = $this->getUniqueId();
throw new InvalidRouteException('Unable to resolve the request "' . ($id === '' ? $route : $id . '/' . $route) . '".');
}
}
/**
* Creates a controller instance based on the given route.
* 根据给定的路径创建一个控制器实例。
* The route should be relative to this module. The method implements the following algorithm
* to resolve the given route:
* 相对这个模块的路径。该方法实现了以下算法来解决给定的路径:
* 1. If the route is empty, use [[defaultRoute]]; 路径为空,调用默认的路径
* 2. If the first segment of the route is a valid module ID as declared in [[modules]],
* call the module's `createController()` with the rest part of the route;
* 3. If the first segment of the route is found in [[controllerMap]], create a controller
* based on the corresponding configuration found in [[controllerMap]];
* 4. The given route is in the format of `abc/def/xyz`. Try either `abc\DefController`
* or `abc\def\XyzController` class within the [[controllerNamespace|controller namespace]].
*
* If any of the above steps resolves into a controller, it is returned together with the rest
* part of the route which will be treated as the action ID. Otherwise, false will be returned.
*
* @param string $route the route consisting of module, controller and action IDs.
* 由模块、控制器和动作标识组成的路径。
* @return array|boolean If the controller is created successfully, it will be returned together
* with the requested action ID. Otherwise false will be returned.
* 如果控制器成功创建,将与被请求的操作标识一起返回,否则将返回false。
* @throws InvalidConfigException if the controller class and its file do not match.
* 如果控制器类及其文件不匹配,抛出异常
*/
public function createController($route)
{
if ($route === '') {//路径为空,调用默认的路径
$route = $this->defaultRoute;
}
// double slashes or leading/ending slashes may cause substr problem
$route = trim($route, '/'); //去掉两边的反斜线,
if (strpos($route, '//') !== false) {
return false; //如果路径中包含双斜线,返回false
}
if (strpos($route, '/') !== false) {
list ($id, $route) = explode('/', $route, 2);//将路径按反斜线分割为两个元素的数组,
} else {
$id = $route;
$route = '';
}
// module and controller map take precedence 优先判断模块和控制器映射
if (isset($this->controllerMap[$id])) {
//如果$id是控制器ID,实例化控制器,返回控制器实例和后面的路径$route
$controller = Yii::createObject($this->controllerMap[$id], [$id, $this]);
return [$controller, $route];
}
$module = $this->getModule($id);
if ($module !== null) {//如果$id是模块ID,实例化控制器,返回控制器实例和后面的路径$route
return $module->createController($route);
}
if (($pos = strrpos($route, '/')) !== false) {
//上面两种情况都不是,则表示还有子模块,构造子模块的标识
$id .= '/' . substr($route, 0, $pos);
$route = substr($route, $pos + 1);
}
$controller = $this->createControllerByID($id);
if ($controller === null && $route !== '') {//实例化控制器 组装控制器实例和后面的路径$route
$controller = $this->createControllerByID($id . '/' . $route);
$route = '';
}
//存在返回控制器实例和后面的路径$route,否则返回false
return $controller === null ? false : [$controller, $route];
}
/**
* Creates a controller based on the given controller ID.
* 根据给定的控制器标识创建控制器
* The controller ID is relative to this module. The controller class
* should be namespaced under [[controllerNamespace]].
* 当前模块的控制器标识,控制器类应在 [[controllerNamespace]]的命名空间下
* Note that this method does not check [[modules]] or [[controllerMap]].
*
* @param string $id the controller ID 控制器标识
* @return Controller the newly created controller instance, or null if the controller ID is invalid.
* 新创建的控制器实例,为null则控制器标识无效
* @throws InvalidConfigException if the controller class and its file name do not match.
* This exception is only thrown when in debug mode.
*/
public function createControllerByID($id)
{
$pos = strrpos($id, '/');
if ($pos === false) {
$prefix = ''; //是否包含反斜线,
$className = $id;
} else {//将路径按反斜线分割为两个元素
$prefix = substr($id, 0, $pos + 1);
$className = substr($id, $pos + 1);
}
if (!preg_match('%^[a-z][a-z0-9\\-_]*$%', $className)) {
return null;//正则判断是否符合规则
}
if ($prefix !== '' && !preg_match('%^[a-z0-9_/]+$%i', $prefix)) {
return null;
}
//组装控制器名
$className = str_replace(' ', '', ucwords(str_replace('-', ' ', $className))) . 'Controller';
$className = ltrim($this->controllerNamespace . '\\' . str_replace('/', '\\', $prefix) . $className, '\\');
if (strpos($className, '-') !== false || !class_exists($className)) {
return null; //控制器名有 ‘-’或不存在则为null
}
if (is_subclass_of($className, 'yii\base\Controller')) {//检查对象是否有父类或子类
return Yii::createObject($className, [$id, $this]); //创建控制器
} elseif (YII_DEBUG) {
throw new InvalidConfigException("Controller class must extend from \\yii\\base\\Controller.");
} else {
return null;
}
}
/**
* This method is invoked right before an action within this module is executed.
* 当前模块的Action执行前调用的方法,将触发[[EVENT_BEFORE_ACTION]]事件
* The method will trigger the [[EVENT_BEFORE_ACTION]] event. The return value of the method
* will determine whether the action should continue to run.
* 如果返回true,Action方法才会执行
* If you override this method, your code should look like the following:
*
* ```php
* public function beforeAction($action)
* {
* if (parent::beforeAction($action)) {
* // your custom code here
* return true; // or false if needed
* } else {
* return false;
* }
* }
* ```
*
* @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);//触发beforeAction事件
return $event->isValid;
}
/**
* This method is invoked right after an action within this module is executed.
* 当前模块的Action执行后调用的方法,触发[[EVENT_AFTER_ACTION]]事件
* The method will trigger the [[EVENT_AFTER_ACTION]] event. The return value of the method
* will be used as the action return value.
* 如果返回true,后面的代码才会继续执行
* If you override this method, your code should look like the following:
*
* ```php
* public function afterAction($action, $result)
* {
* $result = parent::afterAction($action, $result);
* // your custom code here
* return $result;
* }
* ```
*
* @param Action $action the action just executed. 执行的操作
* @param mixed $result the action return result. 执行结果
* @return mixed the processed action result. 处理结果
*/
public function afterAction($action, $result)
{
$event = new ActionEvent($action);
$event->result = $result;
$this->trigger(self::EVENT_AFTER_ACTION, $event);//触发beforeAction事件
return $event->result;
}
}