Laravel 门面执行流程的简单分析

  1. 我们以Route::get('' , '')这个基本的路由门面来进行基本解析
  2. 首先我们需要知道门面(Facades)的配置文件在config/app.alias,由此可知Route类对应的类
    <?php
    
    namespace Illuminate\Support\Facades;
    
    /**
     * @see \Illuminate\Routing\Router
     */
    class Route extends Facade
    {
        /**
         * Get the registered name of the component.
         *
         * @return string
         */
        protected static function getFacadeAccessor()
        {
            return 'router';
        }
    }
    

    在这个类中我们发现没有找到静态方法get,由于Route继承自Facade 所以我们进入Facade发现也并没有找到静态方法get,但是我们发现有一个魔术方法__callStatic()。所以当找不到静态方法get时会调用此魔术方法。调用此方法的我们由以下代码发现函数会调用getFacadeRoot()方法

     public static function __callStatic($method, $args)
        {
            $instance = static::getFacadeRoot();
    
            if (! $instance) {
                throw new RuntimeException('A facade root has not been set.');
            }
    
            switch (count($args)) {
                case 0:
                    return $instance->$method();
                case 1:
                    return $instance->$method($args[0]);
                case 2:
                    return $instance->$method($args[0], $args[1]);
                case 3:
                    return $instance->$method($args[0], $args[1], $args[2]);
                case 4:
                    return $instance->$method($args[0], $args[1], $args[2], $args[3]);
                default:
                    return call_user_func_array([$instance, $method], $args);
            }
        }
    public static function getFacadeRoot()
        {
            return static::resolveFacadeInstance(static::getFacadeAccessor());
        }

    我们通过代码发现会调用门面的getFacadeAccessor()这个方法是每个门面类必须要实现的,该方法就是返回别名类所对应的服务容器类的名称,router对应的服务容器位于

    Illuminate\Routing\Router

    接着通过static::$app[$name]最终实现调用get方法  

    protected static function resolveFacadeInstance($name)
        {
            if (is_object($name)) {
                return $name;
            }
    
            if (isset(static::$resolvedInstance[$name])) {
                return static::$resolvedInstance[$name];
            }
    
            return static::$resolvedInstance[$name] = static::$app[$name];
        }

     

转载于:https://my.oschina.net/u/3054299/blog/1540579

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值