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 關注
- 138 瀏覽
添加回答
舉報