yii2源码学习笔记(八)

时间:2023-03-08 16:32:57

Action是所有控制器的基类,接下来了解一下它的源码。yii2\base\Action.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; /**
* Action is the base class for all controller action classes.
* 是所有控制器的基类
* Action provides a way to divide a complex controller into
* smaller actions in separate class files.
* 控制器提供了一种重复使用操作方法的代码,在多个控制器或不同的项目中使用
* Derived classes must implement a method named `run()`. This method
* will be invoked by the controller when the action is requested.
* The `run()` method can have parameters which will be filled up
* with user input values automatically according to their names.
* 派生类必须实现一个名为run()的方法,这个方法会在控制器被请求时调用。
* 它可以有参数,将用户输入值的根据他们的名字自动填补。
* For example, if the `run()` method is declared as follows:
* 例:run()方法调用声明如下:
* ~~~
* public function run($id, $type = 'book') { ... }
* ~~~
*
* And the parameters provided for the action are: `['id' => 1]`.
* Then the `run()` method will be invoked as `run(1)` automatically.
* 并且提供了操作的参数 ['id'=>1];
* 当run(1)时自动调用run();
* @property string $uniqueId The unique ID of this action among the whole application. This property is
* read-only.
* 整个应用程序中,这一行动的唯一标识。此属性是只读
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Action extends Component
{
/**
* @var string ID of the action ID的动作
*/
public $id;
/**
* @var Controller|\yii\web\Controller the controller that owns this action
* 拥有这一行动的控制器
*/
public $controller; /**
* Constructor.
* 构造函数
* @param string $id the ID of this action 这一行动的ID
* @param Controller $controller the controller that owns this action 拥有这一行动的控制器
* @param array $config name-value pairs that will be used to initialize the object properties
* 用来初始化对象属性的 name-value
*/
public function __construct($id, $controller, $config = [])
{
$this->id = $id;
$this->controller = $controller;
//调用父类的__construct()方法
parent::__construct($config);
} /**
* Returns the unique ID of this action among the whole application.
* 返回整个应用程序中的唯一ID。
* @return string the unique ID of this action among the whole application.
* 在整个应用程序中,这一行动的唯一ID。
*/
public function getUniqueId()
{
return $this->controller->getUniqueId() . '/' . $this->id;
} /**
* Runs this action with the specified parameters. 用指定的参数运行此操作。
* This method is mainly invoked by the controller. 该方法主要由控制器调用。
*
* @param array $params the parameters to be bound to the action's run() method.绑定到行动的run()方法的参数。
* @return mixed the result of the action 行动的结果 命名参数是否有效的
* @throws InvalidConfigException if the action class does not have a run() method
* 如果动作类没有run()方法 扔出异常
*/
public function runWithParams($params)
{
if (!method_exists($this, 'run')) {//如果动作类没有run()方法 抛出异常
throw new InvalidConfigException(get_class($this) . ' must define a "run()" method.');
}
//调用bindActionParams()方法将参数绑定到动作。
$args = $this->controller->bindActionParams($this, $params);
//记录跟踪消息
Yii::trace('Running action: ' . get_class($this) . '::run()', __METHOD__);
if (Yii::$app->requestedParams === null) {
//请求的动作提供的参数
Yii::$app->requestedParams = $args;
}
if ($this->beforeRun()) {
//执行run()方法
$result = call_user_func_array([$this, 'run'], $args);
$this->afterRun(); return $result;
} else {
return null;
}
} /**
* This method is called right before `run()` is executed.
* ` run() `执行前方法被调用。
* You may override this method to do preparation work for the action run.
* 可以重写此方法,为该操作运行的准备工作。
* If the method returns false, it will cancel the action.
* 如果该方法返回false,取消该操作。
* @return boolean whether to run the action.
*/
protected function beforeRun()
{
return true;
} /**
* This method is called right after `run()` is executed. ` run() `执行后 方法被调用。
* You may override this method to do post-processing work for the action run.
* 可以重写此方法来处理该动作的后续处理工作。
*/
protected function afterRun()
{
}
}

接下来我们看一下事件参数相关重要的一个类ActionEvent。yii2\base\ActionEvent.php

 <?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/ namespace yii\base; /**
* ActionEvent represents the event parameter used for an action event.
* 用于操作事件的事件参数
* By setting the [[isValid]] property, one may control whether to continue running the action.
* 通过设置[[isValid]]属性,控制是否继续运行action。
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class ActionEvent extends Event
{
/**
* @var Action the action currently being executed
* 目前正在执行的行动
*/
public $action;
/**
* @var mixed the action result. Event handlers may modify this property to change the action result.
* 操作结果 事件处理程序可以修改此属性来更改操作结果。
*/
public $result;
/**
* @var boolean whether to continue running the action. Event handlers of
* [[Controller::EVENT_BEFORE_ACTION]] may set this property to decide whether
* to continue running the current action.
* 是否继续运行该动作。设置[[Controller::EVENT_BEFORE_ACTION]]属性决定是否执行当前的操作
*/
public $isValid = true; /**
* Constructor.构造函数。
* @param Action $action the action associated with this action event.与此事件相关联的动作。
* @param array $config name-value pairs that will be used to initialize the object properties
* 用来初始化对象属性的 name-value
*/
public function __construct($action, $config = [])
{
$this->action = $action;
parent::__construct($config);
}
}

今天最后看一下操作过滤器的基类吧ActionFilter。yii2\base\ActionFilter.php。

 <?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/ namespace yii\base; /**
* ActionFilter is the base class for action filters.
* 是操作过滤器的基类。
* An action filter will participate in the action execution workflow by responding to
* the `beforeAction` and `afterAction` events triggered by modules and controllers.
* 一个操作过滤器将参与行动的执行工作流程,通过触发模型和控制器的`beforeAction` 和`afterAction` 事件
* Check implementation of [[\yii\filters\AccessControl]], [[\yii\filters\PageCache]] and [[\yii\filters\HttpCache]] as examples on how to use it.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class ActionFilter extends Behavior
{
/**
* @var array list of action IDs that this filter should apply to. If this property is not set,
* then the filter applies to all actions, unless they are listed in [[except]].
* 操作标识列表。如果该属性未设置,过滤器适用于所有的行动,除非它们被列入[[except]]中。
* If an action ID appears in both [[only]] and [[except]], this filter will NOT apply to it.
* 如果一个操作ID 出现在[[only]] 和[[except]]中,该筛选器将不适用它
* Note that if the filter is attached to a module, the action IDs should also include child module IDs (if any)
* and controller IDs.
* 如果过滤器是链接到一个模块,操作检测还应包括子模块和控制器
*
* @see except
*/
public $only;
/**
* @var array list of action IDs that this filter should not apply to.
* 此筛选器不应适用于操作ID。
* @see only
*/
public $except = []; /**
* @inheritdoc
* 将行为对象附加到组件。
*/
public function attach($owner)
{
$this->owner = $owner;
$owner->on(Controller::EVENT_BEFORE_ACTION, [$this, 'beforeFilter']);
} /**
* @inheritdoc
* 将行为对象和组件分离。
*/
public function detach()
{
if ($this->owner) {
$this->owner->off(Controller::EVENT_BEFORE_ACTION, [$this, 'beforeFilter']);
$this->owner->off(Controller::EVENT_AFTER_ACTION, [$this, 'afterFilter']);
$this->owner = null;
}
} /**
* @param ActionEvent $event 在动作之前调用
*/
public function beforeFilter($event)
{
if (!$this->isActive($event->action)) {
return;
} $event->isValid = $this->beforeAction($event->action);
if ($event->isValid) {
// call afterFilter only if beforeFilter succeeds beforeFilter 执行成功调用afterFilter
// beforeFilter and afterFilter should be properly nested 两者要配合应用
$this->owner->on(Controller::EVENT_AFTER_ACTION, [$this, 'afterFilter'], null, false);
} else {
$event->handled = true;
}
} /**
* @param ActionEvent $event
*/
public function afterFilter($event)
{
$event->result = $this->afterAction($event->action, $event->result);
$this->owner->off(Controller::EVENT_AFTER_ACTION, [$this, 'afterFilter']);
} /**
* 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.
* @param Action $action the action to be executed.要执行的动作
* @return boolean whether the action should continue to be executed.
* 是否应继续执行该动作。
*/
public function beforeAction($action)
{
return true;
} /**
* This method is invoked right after an action is executed.
* 此方法是在执行动作之后调用的。
* You may override this method to do some postprocessing for the action.
* @param Action $action the action just executed. 刚刚执行的动作
* @param mixed $result the action execution result 行动执行结果
* @return mixed the processed action result. 处理结果。
*/
public function afterAction($action, $result)
{
return $result;
} /**
* Returns a value indicating whether the filer is active for the given action.
* 返回一个值,给定的过滤器的行动是否为是积极的。
* @param Action $action the action being filtered 被过滤的动作
* @return boolean whether the filer is active for the given action.
* 给定的过滤器的行动是否为是积极的。
*/
protected function isActive($action)
{
if ($this->owner instanceof Module) {
// convert action uniqueId into an ID relative to the module
$mid = $this->owner->getUniqueId();
$id = $action->getUniqueId();
if ($mid !== '' && strpos($id, $mid) === ) {
$id = substr($id, strlen($mid) + );
}
} else {
$id = $action->id;
}
return !in_array($id, $this->except, true) && (empty($this->only) || in_array($id, $this->only, true));
}
}