Home > Article > PHP Framework > Detailed explanation of the relationship between Contracts, ServiceContainer, ServiceProvider and Facades in laravel
Contracts
, ServiceContainer
, ServiceProvider
, Facades
1.Contracts
Contract , the contract, that is, the interface, defines some rules, and everyone who implements this interface must implement the methods inside;
2.ServiceContainer
, implement Contracts
, specifically Logical implementation;
3.ServiceProvider
, the service provider of serviceContainer
, returns the instantiation of ServiceContainer
for use elsewhere, you can Add it to the provider
of app/config
, and it will be automatically registered in the container;
4.Facades
, simplifyServiceProvider
calling method, and can statically call the methods in ServiceContainer
;
implementation
Contracts
The interface can be written or not, and will not be defined here;
Define a ServiceContainer
to implement specific functions
namespace App\Helper; class MyFoo { public function add($a, $b) { return $a+$b; } }
Define a ServiceProvider
for use elsewhere ServiceContain
<?php namespace App\Providers; use App\Helper\MyFoo; //要服务的Container use Illuminate\Support\ServiceProvider; use App; class MyFooServiceProvider extends ServiceProvider { public function boot(){} //注册到容器中 public function register() { //可以这么绑定,这需要use App; App::bind("myfoo",function(){ return new MyFoo(); }); //也可以这么绑定 $this->app->bind("myfoo", function(){ return new MyFoo(); }); } }
at## Add ServiceProvider
to the providers
array in #app/config.php to allow the system to automatically register
App\Providers\MyFooServiceProvider::class ,
public function two($id=null) { //从系统容器中获取实例化对象 $myfoo = App::make("myfoo"); echo $myfoo->add(1,2); }This is too troublesome, and you still need to use
make To get the object, for simplicity, you can use the facade function, define the facade
MyFooFacade
namespace App\Facades; use Illuminate\Support\Facades\Facade; class MyFooFacade extends Facade { protected static function getFacadeAccessor() { //这里返回的是ServiceProvider中注册时,定义的字符串 return 'myfoo'; } }and you can call it directly in the controller
use App\Facades\MyFooFacade; public function two($id=null) { //从系统容器中获取实例化对象 $myfoo = App::make("myfoo"); echo $myfoo->add(1,2); //使用门面 echo MyFooFacade::add(4,5); }In general, after customizing a class, in order to facilitate its use elsewhere, you can use service providers and facades. Recommended: "
laravel tutorial"
The above is the detailed content of Detailed explanation of the relationship between Contracts, ServiceContainer, ServiceProvider and Facades in laravel. For more information, please follow other related articles on the PHP Chinese website!