Laravel如何创建服务器提供者实例代码

2019-11-13,,,,

前言

Laravel服务器容器:是用于管理类依赖和执行依赖注入的工具。下面我们演示下如何创建服务器提供者,它是Laravel的核心。话不多说了,来一起看看详细的介绍吧

在app/Contracts目录下创建TestContract.php文件,其内容为:

<?php 
namespace App\Contracts; 

interface TestContract { 
 public function callMe($controller); 
}

在app/Services目录下创建TestService.php文件,其内容为:

<?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中添加内容,以便进行注册:

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

创建1个服务提供类:

php artisan make:provider RiakServiceProvider 

其内容为:

<?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中添加如下内容:

<?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"); 
 } 
}

访问浏览器可以得到如下的结果:

"Call me from TestServiceProvider in IndexController" 

另外,还可以使用App的make方法进行调用。

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

其结果也是一样的。

参考文章:

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对北冥有鱼的支持。

《Laravel如何创建服务器提供者实例代码.doc》

下载本文的Word格式文档,以方便收藏与打印。