Home  >  Article  >  PHP Framework  >  Detailed explanation of the relationship between Contracts, ServiceContainer, ServiceProvider and Facades in laravel

Detailed explanation of the relationship between Contracts, ServiceContainer, ServiceProvider and Facades in laravel

藏色散人
藏色散人forward
2020-04-16 11:42:282948browse

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

ContractsThe 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

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 ,

It can be used at this time. Suppose it is used in the controller

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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete