Laravel's "facade" and "contract" issues:
There are two questions:
1. What are the usage scenarios of these two things?
2. I can’t understand why these two words are used. I feel that they are incompatible. Are these two words related to their functions?
给我你的怀抱2017-05-16 16:49:41
Simply put: Appearance
(the Facade
you are talking about) is the implementation of Appearance mode
. 外观
(你说的门面
)是外观模式
的实现。协议
(你说的契约
)是工厂方法模式
或抽象工厂模式
Protocol
(the Contract
you are talking about) is the implementation of Factory Method Pattern
or Abstract Factory Pattern
.
Read the design patterns and you will gain a lot.
高洛峰2017-05-16 16:49:41
You must first learn to use dependency injection containers.
Laravel’s Facade is a shortcut for calling services from the container.
When there is no Facade, you may have to get a service/object like this and then call:
$service = App::make('some_service');
$service->doSomething();
Because you registered 'some_service'
,所以容器能make
an instance in the container for you.
Facade just simplifies this usage process in a static way. The bottom layer uses __callStatic
to pass functions and parameters to service instances:
class SomeService extends Facade
{
protected static function getFacadeAccessor()
{
return 'some_service'; // 这是容器里的键
}
}
SomeService::doSomething(); // 底层和第一段代码是类似的
Contract is a bunch of interfaces that come with the framework, which can be implemented through dependency injection.
public function index(SomeService $service) { // 等服务容器注入一个SomeService。
$service->doSomething();
}
Facade and Contract are just different ways of using dependency injection containers. To use Facade, you go to the container to get it yourself (use the container as a Service Locator), and to use Contract, you wait for the container to inject dependencies.
曾经蜡笔没有小新2017-05-16 16:49:41
Facade, to put it simply, is to give an alias to the service bound in the service container, using the class_alias function
For example, App corresponds to the Container class.
A contract, as the name suggests, is a rule that both parties recognize and abide by, and "interface" also has these characteristics. The poster asked, it should be "interface-oriented programming". Interface-oriented programming is difficult to explain clearly. I am still relatively inexperienced. , the poster needs more practice and experience, please forgive me...