zoukankan      html  css  js  c++  java
  • yii2框架随笔30

    今天来看console/Application

    <?php
    /**
     * @link http://www.yiiframework.com/
     * @copyright Copyright (c) 2008 Yii Software LLC
     * @license http://www.yiiframework.com/license/
     */
    namespace yiiconsole;
    use Yii;
    use yiibaseInvalidRouteException;
    /**
     * Application represents a console application.
     * 应用程序代表一个控制台应用程序。
     * Application extends from [[yiiaseApplication]] by providing functionalities that are
     * specific to console requests. In particular, it deals with console requests
     * through a command-based approach:
     * 应用范围从[ [yiiaseApplication]]所提供的功能是特定在控制台请求的
    
     * - A console application consists of one or several possible user commands;
     * 一个控制台应用程序包含一个或几个可能的用户命令;
     * - Each user command is implemented as a class extending [[yiiconsoleController]];
     * 每一个用户命令实现为一个类扩展[[yiiconsoleController]];
     * - 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 <qiang.xue@gmail.com>
     * @since 2.0
     */
    class Application extends yiibaseApplication
    {
        /**
         * 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
    ");
                        }
                    }
                }
            }
            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'] = 'yiiconsolecontrollersHelpController';
            }
        }
        /**
         * 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' => 'yiiconsolecontrollersMessageController',
                'help' => 'yiiconsolecontrollersHelpController',
                'migrate' => 'yiiconsolecontrollersMigrateController',
                'cache' => 'yiiconsolecontrollersCacheController',
                'asset' => 'yiiconsolecontrollersAssetController',
                'fixture' => 'yiiconsolecontrollersFixtureController',
            ];
        }
        /**
         * @inheritdoc
         */
        public function coreComponents()
        {
            // 将console的Request/Response以及ErrorHandler合并到核心组件中
            return array_merge(parent::coreComponents(), [
                'request' => ['class' => 'yiiconsoleRequest'],
                'response' => ['class' => 'yiiconsoleResponse'],
                'errorHandler' => ['class' => 'yiiconsoleErrorHandler'],
            ]);
        }
    }
  • 相关阅读:
    【洛谷 P4721】【模板】—分治FFT(CDQ分治+NTT)
    【Comet OJ】模拟赛测试 Day2题解
    【Comet OJ】模拟赛测试 Day2题解
    将本地文件夹push到github仓库
    2017-3-7
    彻底理解https!
    2017-3-2 智慧吉首调研工作
    java再巩固
    2017-3-1
    不错的博客哦
  • 原文地址:https://www.cnblogs.com/taokai/p/5487538.html
Copyright © 2011-2022 走看看