- 我们以Route::get('' , '')这个基本的路由门面来进行基本解析
- 首先我们需要知道门面(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