欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Laravel如何創(chuàng)建服務(wù)器提供者實(shí)例代碼

 更新時(shí)間:2019年04月15日 10:53:40   作者:我勒個(gè)去  
這篇文章主要給大家介紹了關(guān)于Laravel如何創(chuàng)建服務(wù)器提供者的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Laravel具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧

前言

Laravel服務(wù)器容器:是用于管理類依賴和執(zhí)行依賴注入的工具。下面我們演示下如何創(chuàng)建服務(wù)器提供者,它是Laravel的核心。話不多說了,來一起看看詳細(xì)的介紹吧

在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)容,以便進(jìn)行注冊:

... 
App\Providers\RiakServiceProvider::class,

創(chuàng)建1個(gè)服務(wù)提供類:

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個(gè)方法,其中register方法用于注冊服務(wù),而boot用于引導(dǎo)服務(wù)。

在控制器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方法進(jìn)行調(diào)用。

public function index(){ 
 $test = App::make('test'); 
 $test->callMe('IndexController'); 
 }

其結(jié)果也是一樣的。

參考文章:

  • https://laravelacademy.org/post/796.html
  • https://laravelacademy.org/post/93.html

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對腳本之家的支持。

相關(guān)文章

最新評論