1 回答

TA贡献1829条经验 获得超7个赞
在 Laravel 应用程序中,外观是一个提供从容器访问对象的类。完成这项工作的机器在 Facade 类中。Laravel 的外观,以及您创建的任何自定义外观,都将扩展基础 Illuminate\Support\Facades\Facade 类。
Facade 基类使用 __callStatic() 魔术方法将来自外观的调用推迟到从容器解析的对象。在下面的示例中,调用了 Laravel 缓存系统。看一眼这段代码,人们可能会认为静态方法 get 正在 Cache 类上被调用:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
class UserController extends Controller
{
/**
* Show the profile for the given user.
*
* @param int $id
* @return Response
*/
public function showProfile($id)
{
$user = Cache::get('user:'.$id);
return view('profile', ['user' => $user]);
}
}
请注意,在文件顶部附近,我们正在“导入” Cache 外观。这个门面用作访问 Illuminate\Contracts\Cache\Factory 接口的底层实现的代理。我们使用外观进行的任何调用都将传递给 Laravel 缓存服务的底层实例。
如果我们查看 Illuminate\Support\Facades\Cache 类,您会发现没有静态方法 get:
class Cache extends Facade {
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor() { return 'cache'; } }
相反,Cache 外观扩展了基本外观类并定义了方法 getFacadeAccessor()。此方法的工作是返回服务容器绑定的名称。当用户在 Cache 外观上引用任何静态方法时,Laravel 会从服务容器解析缓存绑定并针对该对象运行请求的方法(在本例中为 get)。
- 1 回答
- 0 关注
- 122 浏览
添加回答
举报