Laravel How to Create Server Provider Instance Code

  • 2021-12-09 08:24:41
  • OfStack

Preface

Laravel Server Container: A tool for managing class dependencies and performing dependency injection. Let's demonstrate how to create a server provider, which is the core of Laravel. I don't have much to say. Let's take a look at the detailed introduction

Create the TestContract. php file in the app/Contracts directory with the following contents:


<?php 
namespace App\Contracts; 

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

Create the TestService. php file in the app/Services directory with the following contents:


<?php 
namespace App\Services; 
use App\Contracts\TestContract; 

class TestService implements TestContract { 
 public function callMe($controller){ 
 dd("Call me from TestServiceProvider in ".$controller); 
 } 
}

Add content to providers in the config/app. php file for registration:


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

Create 1 service provider class:


php artisan make:provider RiakServiceProvider 

Its contents are as follows:


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

Two methods are provided in ServiceProvider, where the register method is used to register the service and the boot is used to boot the service.

Add the following to the controller 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"); 
 } 
}

Visiting the browser can get the following results:

"Call me from TestServiceProvider in IndexController"

In addition, it can be called using the make method of App.


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

The result is also the same.

Reference article:

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

Summarize


Related articles: