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?
Simply put:
Appearance
(theFacade
you are talking about) is the implementation ofAppearance mode
.外观
(你说的门面
)是外观模式
的实现。协议
(你说的契约
)是工厂方法模式
或抽象工厂模式
Protocol
(theContract
you are talking about) is the implementation ofFactory Method Pattern
orAbstract Factory Pattern
.Read the design patterns and you will gain a lot.
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:
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:Contract is a bunch of interfaces that come with the framework, which can be implemented through dependency injection.
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.
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...