contracts, ServiceContainer, serviceprovider, facades
- Contracts contract, contract, that is, interface, define some rules, each implementation of this interface to implement the method inside
- ServiceContainer implementation of contracts, concrete logic implementation
- ServiceProvider ServiceContainer service provider, returns the instantiation of the ServiceContainer for use elsewhere, can be added to App/config provider, will be automatically registered in the container
- Facades simplifies the way serviceprovider is called, and can call methods in ServiceContainer statically
Implement contracts interface can write or not write, here does not define a servicecontainer to achieve the specific function
namespace App\helper; class myfoo{ publicfunction Add ($a$b) { return$a+$b; }}
Define a serviceprovider for other places to use Servicecontain
<?phpnamespace app\providers; UseApp\helper\myfoo;//the container to serve UseIlluminate\support\serviceprovider; UseApp;classMyfooserviceproviderextendsserviceprovider{ Public functionboot () {}//registering in a container Public functionRegister () {//can be so binding, which requires use of the App;App::bind ("Myfoo",function(){ return NewMyfoo (); }); //can also be so binding $this->app->bind ("Myfoo",function(){ return NewMyfoo (); }); }}
Add serviceprovider to the providers array in app/config.php to let the system register automatically
App\providers\myfooserviceprovider::class,
It can be used at this time, assuming that the controller uses
Public function ($id=null) { // Get instantiated object from System container $ Myfoo = App::make ("Myfoo"); Echo $myfoo->add;}
This is too cumbersome, you need to use make to get objects, for the sake of simplicity, you can use the façade function, define the façade Myfoofacade
namespace App\facades; Use Illuminate\support\facades\facade; class extends facade{ protectedstaticfunction getfacadeaccessor () { // return here is serviceprovider when registering, define the string return ' Myfoo ';} }
You can call it directly in the controller.
Use App\facades\myfoofacade; Public function ($id=null) { // Get instantiated object from System container $ Myfoo = App::make ("Myfoo"); Echo $myfoo->add (); // using the façade Echo Myfoofacade::add (4,5
In general, a class has been customized so that service providers and facades can be used in order to make them easier to use elsewhere
Contracts, ServiceContainer, serviceprovider, facades relations in Laravel