Home >Backend Development >PHP Tutorial >An in-depth analysis of the proxy pattern of PHP design patterns_PHP tutorial
Proxy mode (Proxy), which is an enhancement to a simple handler (or pointer), is used to reference an object: this pointer is replaced by a proxy (Proxy) object, which is located between the client and the real executor In between, pointers have a hook that can be exploited by multiple targets.
Technically speaking, this pattern inserts a proxy object between the client and the real subject (RealSubject), maintaining the subject interface and delegating its methods in different ways. Agents can do everything transparently: lazily create RealSubjects or load data, exchange messages with other machines, copy-on-write policies, etc. This is somewhat similar to an HTTP proxy, where clients (such as browsers) and applications rely on contact with the HTTP server. The proxy can complete other tasks while managing the connection, such as access control and caching large download files.
The object graph of the proxy mode is similar in structure to the object graph of the decoration mode, but the purpose of expression is different. The decorator dynamically adds behavior to the object, while the proxy controls access from the client. Additionally, the agent only creates RealSubjects when needed.
Participants:
◆Client: depends on the subject implementation;
◆Subject: abstraction of RealSubject;
◆RealSubject: Complete costly work or contain a large amount of data;
◆Proxy (Proxy): Provide a consistent reference to the Subject for the Client, and only create a RealSubject instance or interact with the RealSubject when needed Instance communication.
The following are two widely used examples of proxy patterns:
1. Object-relational mapping (Orms) creates proxies as subclasses of entity classes at runtime , to implement lazy loading (virtual proxy), this proxy will cover all entity methods, append a loader in front, and will not contain any data before the method is actually called. Orms proxy supports bidirectional relationships between objects, without loading the entire Databases because they are placed at the boundaries of the currently loaded object graph.
2. Java RMI uses remote proxy objects (remote proxies). When their methods are called, the proxy serializes the parameters, performs the request on the network, and delegates the call to the real object on another node. This technology allows transparency You can call remote objects without worrying about whether they are on the same machine, but this transparency can easily slow down execution.
The following code example implements an ImageProxy to defer the loading of image data.