yii2框架随笔30

今天来看console/Application.php

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */
namespace yii\console;
use Yii;
use yii\base\InvalidRouteException;
/**
 * Application represents a console application.
 * 应用程序代表一个控制台应用程序。
 * Application extends from [[\yii\base\Application]] by providing functionalities that are
 * specific to console requests. In particular, it deals with console requests
 * through a command-based approach:
 * 应用范围从[ [\yii\base\Application]]所提供的功能是特定在控制台请求的

 * - A console application consists of one or several possible user commands;
 * 一个控制台应用程序包含一个或几个可能的用户命令;
 * - Each user command is implemented as a class extending [[\yii\console\Controller]];
 * 每一个用户命令实现为一个类扩展[[\yii\console\Controller]];
 * - User specifies which command to run on the command line;
 * 用户指定在命令行上运行的命令;
 * - The command processes the user request with the specified parameters.
 * 命令处理用户请求的指定参数。
 * The command classes should be under the namespace specified by [[controllerNamespace]].
 * 命令类应该在命名空间指定的[[controllernamespace]]。
 * Their naming should follow the same naming convention as controllers. For example, the `help` command
 * is implemented using the `HelpController` class.
 * 它们的命名应该遵循相同的命名规则作为控制器。例如,“help”命令采用` helpcontroller `类。
 * To run the console application, enter the following on the command line:
 * 要运行控制台应用程序,在命令行中输入以下命令:
 * ~~~
 * yii <route> [--param1=value1 --param2 ...]
 * ~~~
 *
 *
 * A `help` command is provided by default, which lists available commands and shows their usage.
 * To use this command, simply type:
 * 默认情况下提供了一个帮助命令,它列出了可用的命令,并显示了它们的用法使用此命令,只需键入:
 * ~~~
 * yii help
 * ~~~
 *
 * @author Qiang Xue <[email protected]>
 * @since 2.0
 */
class Application extends \yii\base\Application
{
    /**
     * The option name for specifying the application configuration file path.
     * 指定应用程序配置文件路径的选项名称。
     */
    const OPTION_APPCONFIG = ‘appconfig‘;
    /**
     * @var string the default route of this application. Defaults to ‘help‘,
     * 此应用程序的默认路由。默认为“help”,

     */
    public $defaultRoute = ‘help‘;
    /**
     * @var boolean whether to enable the commands provided by the core framework.
     * 是否启用核心框架提供的命令。
     * Defaults to true.
     * 默认为真。
     */
    public $enableCoreCommands = true;
    /**
     * @var Controller the currently active controller instance
     * 控制器的当前活动控制器实例
     */
    public $controller;
    /**
     * @inheritdoc
     */
    public function __construct($config = [])
    {
        $config = $this->loadConfig($config);
        parent::__construct($config);
    }
    /**
     * Loads the configuration.
     * 加载配置。
     * This method will check if the command line option [[OPTION_APPCONFIG]] is specified.
     * 该方法将检查如果命令行选项[[option_appconfig]]指定。
     * If so, the corresponding file will be loaded as the application configuration.
     * 如果是这样,相应的文件将被加载为应用程序配置。
     * Otherwise, the configuration provided as the parameter will be returned back.
     * 否则,configuration提供的配置参数,将返回的后台。
     * @param array $config the configuration provided in the constructor.
     * 构造函数中提供的配置。
     * @return array the actual configuration to be used by the application.
     * 实际配置要使用的应用程序。
     */
    protected function loadConfig($config)
    {
        if (!empty($_SERVER[‘argv‘])) {
            // $option是--appconfig=
            $option = ‘--‘ . self::OPTION_APPCONFIG . ‘=‘;
            foreach ($_SERVER[‘argv‘] as $param) {
                // 以--appconfig=开头的
                if (strpos($param, $option) !== false) {
                    // 截取出相应的值
                    $path = substr($param, strlen($option));
                    if (!empty($path) && is_file($file = Yii::getAlias($path))) {
                        // 将值对应的文件require进来
                        return require($file);
                    } else {
                        die("The configuration file does not exist: $path\n");
                    }
                }
            }
        }
        return $config;
    }
    /**
     * Initialize the application.
     * 初始化应用程序。
     */
    public function init()
    {
        parent::init();
        // 如果启用核心命令(默认启用)
        if ($this->enableCoreCommands) {
            foreach ($this->coreCommands() as $id => $command) {
                // 如果controllerMap中有相应的controller,就用当前的命令Controller替换掉
                if (!isset($this->controllerMap[$id])) {
                    $this->controllerMap[$id] = $command;
                }
            }
        }
        // ensure we have the ‘help‘ command so that we can list the available commands
        // 确保我们有“help”命令,这样我们就可以列出可用的命令
        if (!isset($this->controllerMap[‘help‘])) {
            $this->controllerMap[‘help‘] = ‘yii\console\controllers\HelpController‘;
        }
    }
    /**
     * Handles the specified request.
     * 处理指定的请求。
     * @param Request $request the request to be handled
     * @return Response the resulting response
     */
    public function handleRequest($request)
    {
        list ($route, $params) = $request->resolve();
        // 记录请求的路由
        $this->requestedRoute = $route;
        // 返回正常是个int值
        $result = $this->runAction($route, $params);
        if ($result instanceof Response) {
            return $result;
        } else {
            $response = $this->getResponse();
            // 设置为response的exitStatus
            $response->exitStatus = $result;
            return $response;
        }
    }
    /**
     * Runs a controller action specified by a route.
     * 运行指定的控制器动作。
     * @param string $route the route that specifies the action.
     * @param array $params the parameters to be passed to the action
     * @return integer the status code returned by the action execution. 0 means normal, and other values mean abnormal.
     * @throws Exception if the route is invalid
     */
    public function runAction($route, $params = [])
    {
        try {
            // 调用父类方法,返回的内容强转成int
            return (int)parent::runAction($route, $params);
        } catch (InvalidRouteException $e) {
            throw new Exception("Unknown command \"$route\".", 0, $e);
        }
    }
    /**
     * Returns the configuration of the built-in commands.
     * 返回内置命令的配置。
     * @return array the configuration of the built-in commands.
     */
    public function coreCommands()
    {
        // 核心命令,及其对应的类
        return [
            ‘message‘ => ‘yii\console\controllers\MessageController‘,
            ‘help‘ => ‘yii\console\controllers\HelpController‘,
            ‘migrate‘ => ‘yii\console\controllers\MigrateController‘,
            ‘cache‘ => ‘yii\console\controllers\CacheController‘,
            ‘asset‘ => ‘yii\console\controllers\AssetController‘,
            ‘fixture‘ => ‘yii\console\controllers\FixtureController‘,
        ];
    }
    /**
     * @inheritdoc
     */
    public function coreComponents()
    {
        // 将console的Request/Response以及ErrorHandler合并到核心组件中
        return array_merge(parent::coreComponents(), [
            ‘request‘ => [‘class‘ => ‘yii\console\Request‘],
            ‘response‘ => [‘class‘ => ‘yii\console\Response‘],
            ‘errorHandler‘ => [‘class‘ => ‘yii\console\ErrorHandler‘],
        ]);
    }
}
时间: 2024-10-03 02:34:39

yii2框架随笔30的相关文章

yii2框架随笔21

今天来看一下BaseYii.php <?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii; use yii\base\InvalidConfigException; use yii\base\InvalidParamExceptio

yii2框架随笔4

接下来我们继续了解Component.php 目录为:vendor/yiisoft/yii2/base/Component.php (接上次的代码) /** * Sets the value of a component property. *设置一个组件属性的值. * This method will check in the following order and act accordingly: *这种方法将检查以下顺序并采取相应的行动: * - a property defined by

yii2框架随笔23

今天继续阅读BaseYii.php <?php /** * Class autoload loader. * 自动装载类加载程序. * This method is invoked automatically when PHP sees an unknown class. * PHP用该方法自动调用一个未知类. * The method will attempt to include the class file according to the following procedure: * 方

yii2框架随笔22

今天继续来看BaseYii.php <?php /** * Returns the root alias part of a given alias. * 返回根别名的一部分,一个给定的别名. * A root alias is an alias that has been registered via [[setAlias()]] previously. * 根别名是已经注册别名通过[[setAlias()]]. * If a given alias matches multiple root

yii2框架随笔3

今天开始阅读vendor/yiisoft/yii2/base/Action.php <?php namespace yii\base;//命名空间 use Yii;//加载Yii文件夹下的Yii.php /** * Action is the base class for all controller action classes. * * Action provides a way to reuse action method code. An action method in an Acti

yii2框架随笔36

今天来看一下vendor/yiisoft/yii2/base/Event.php <?php namespace yii\base; //事件是所有事件类的基类.它封装了参数与事件相关联. //如果一个事件处理程序集[[进行]]是真的,其余的,uninvoked处理程序将不再被称为处理事件. //另外,添加一个事件处理程序时,额外的数据可能被传递和可以通过[[数据]]属性调用事件处理程序时. class Event extends Object { /** * @var string the e

yii2框架随笔37

vendor/yiisoft/yii2/base/Event.php <?php namespace yii\base; //事件是所有事件类的基类.它封装了参数与事件相关联. //如果一个事件处理程序集[[进行]]是真的,其余的,uninvoked处理程序将不再被称为处理事件. //另外,添加一个事件处理程序时,额外的数据可能被传递和可以通过[[数据]]属性调用事件处理程序时. class Event extends Object { /** * @var string the event n

yii2框架随笔35

今天来看vendor/yiisoft/yii2/base/Event.php <?php namespace yii\base; //事件是所有事件类的基类.它封装了参数与事件相关联. //如果一个事件处理程序集[[进行]]是真的,其余的,uninvoked处理程序将不再被称为处理事件. //另外,添加一个事件处理程序时,额外的数据可能被传递和可以通过[[数据]]属性调用事件处理程序时. class Event extends Object { /** * @var string the eve

yii2框架随笔25

今天来看Container.php,yii2的容器代码. <?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\di; use ReflectionClass; use yii\base\Component; use yii\bas