前言
Laravel服務器容器:是用于管理類依賴和執(zhí)行依賴注入的工具。下面我們演示下如何創(chuàng)建服務器提供者,它是Laravel的核心。話不多說了,來一起看看詳細的介紹吧
在app/Contracts目錄下創(chuàng)建TestContract.php文件,其內(nèi)容為:
?php namespace App\Contracts; interface TestContract { public function callMe($controller); }
在app/Services目錄下創(chuàng)建TestService.php文件,其內(nèi)容為:
?php namespace App\Services; use App\Contracts\TestContract; class TestService implements TestContract { public function callMe($controller){ dd("Call me from TestServiceProvider in ".$controller); } }
在config/app.php文件中providers中添加內(nèi)容,以便進行注冊:
... App\Providers\RiakServiceProvider::class,
創(chuàng)建1個服務提供類:
php artisan make:provider RiakServiceProvider
其內(nèi)容為:
?php namespace App\Providers; use App\Services\TestService; use Illuminate\Support\ServiceProvider; class RiakServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->app->bind("App\Contracts\TestContract",function(){ return new TestService(); }); } }
在ServiceProvider中提供了2個方法,其中register方法用于注冊服務,而boot用于引導服務。
在控制器IndxController中添加如下內(nèi)容:
?php namespace App\Http\Controllers; use App; use Illuminate\Http\Request; use App\Contracts\TestContract; class IndexController extends Controller { public function __construct(TestContract $test){ $this->test = $test; } public function index(){ $this->test->callMe("IndexController"); } }
訪問瀏覽器可以得到如下的結(jié)果:
"Call me from TestServiceProvider in IndexController"
另外,還可以使用App的make方法進行調(diào)用。
public function index(){ $test = App::make('test'); $test->callMe('IndexController'); }
其結(jié)果也是一樣的。
參考文章:
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。