本文講述了Laravel中注冊Facades的步驟。分享給大家供大家參考,具體如下:
在Laravel中將類注冊為Fcade可以使用Ioc容器,每次使用這個類的時候只會初始化一次類,類似單例模式,而且可以像使用靜態方法調用類的方法,下面是在Laravel中注冊Facades的步驟。
1.在項目app目錄的Providers/AppServiceProvider.php中的register方法新增方法,代碼如下。
/** * Register any application services. * * @return void */public function register(){ $this->registerTestModel();}private function registerTestModel(){ $this->app->singleton('testmodel', function ($app) { $model = 'App/Models/Test'; return new $model(); }); $this->app->alias('testmodel', 'App/Models/Test');}
這里把命名空間是App/Models的Test類注冊為單例模式,并且取個別名testmodel.這個Test類的文件位置app/Models/Test.php.
2.建立一個Facade類
在項目根目錄app/Facades目錄新增文件,如Test.php,代碼如下,目錄不存在可以新建一個。
<?phpnamespace App/Facades;use Illuminate/Support/Facades/Facade;class Test extends Facade{ /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'testmodel'; }}
通過繼承Facade,重載getFacadeAccessor方法,返回之前綁定的單例模式的類的別名。
3.使用Facade
經過前面的步驟后,可以使用Test這個Facade了,如下示例是在控制器中使用Facade的方式。
<?phpnamespace App/Http/Controllers;use App/Facades/Test;use Illuminate/Routing/Controller;class TestController extends Controller{ public function __construct() { Test::show(); Test::show(); }}
先看看這個原始類Test.php的內容:
<?phpnamespace App/Models;use Illuminate/Database/Eloquent/Model;class Test extends Model{ protected $table = 'tt'; public static $times = 0; public function __construct() { self::$times++; parent::__construct(); } public function show() { echo self::$times . '<br>'; }}
經過注冊Facade后,調用show方法就是Test::show()的形式,并且類似單例模式不會多次實例化,調用也十分簡單。
PS:以上僅為注冊Facade的方法和步驟,實際項目中可能還需對Model層進行進一步的封裝。
轉自:小談博客 http://www.tantengvip.com/2016/01/laravel-facades-register/