刚接触laravel一周多,最近一直在奇怪为什么代码都是用了类里的静态方法,但是子类和父类里都没有这个静态方法啊。
不解,就一直网上查找,查了laravel的文档 看的迷迷茫茫。 现在也算是有点见解了。
比如laravel里经常这样的代码
//路由文件里
Route::any('login', 'Auth\AuthController@login');
//控制器里跳转
Redirect::back()
// Validator数据验证
Validator::make($input, $rules, $message)
Route 、Redirect、Validator这些类里面都没有any、back、make这些静态方法
例如route.php (在项目\vendor\laravel\framework\src\Illuminate\Support\Facades\Route.php)
<?php
namespace Illuminate\Support\Facades;
class Route extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'router';
}
}
里面根本没有any方法,只有一个静态的getFacadeAccessor()方法,
现在查看一下Facade的父类里也有一个getFacadeAccessor()方法,说明对父类方法进行了重写
/**
* Get the registered name of the component.
*
* @return string
*
* @throws \RuntimeException
*/
protected static function getFacadeAccessor()
{
throw new RuntimeException('Facade does not implement getFacadeAccessor method.');
}
而且如果没有重写getFacadeAccessor方法的话还会抛出没有实现这个方法的异常。
现在再来查看一下父类Facade类里有一个魔术方法 __callStatic
/**
* Handle dynamic, static calls to the object.
*
* @param string $method
* @param array $args
* @return mixed
*
* @throws \RuntimeException
*/
public static function __callStatic($method, $args)
{
$instance = static::getFacadeRoot();
if (! $instance) {
throw new RuntimeException('A facade root has not been set.');
}
return $instance->$method(...$args);
}
__callStatic :当调用的静态方法不存在或权限不足时,会自动调用__callStatic方法。
上面的解释也说了,如果当使用 Route::any的时候,发现没有any这个方法那么 Facade就会自动执行__callStatic魔术方法。
好好查看__callStatic方法的内部就会发现他经过一系列的处理之后还是调用了子类所重写的getFacadeAccessor方法。
//TODO
至于any方法在哪里目前还没找到, 等找到之后再来编写