Proxy Mode and PHP implementation

Source: Internet
Author: User

Agent mode (proxy pattern):

Provides a proxy for an object and controls a reference to the original object by the proxy object. Proxy mode in English is called proxy or surrogate, it is an object-structured pattern

Mode motive:
In some cases, a customer does not want or cannot refer directly to an object, and an indirect reference can be achieved by a third party called a "proxy". A proxy object can act as a mediator between the client and the target object, and can remove content and services that the customer cannot see or add additional services that the customer needs through the proxy object.
By introducing a new object, such as a small picture and a remote proxy object, to implement an operation on a real object or to use a new object as a surrogate for a real object, the implementation mechanism is the proxy mode, which indirectly accesses an object by introducing a proxy object, which is the mode motive of the proxy mode.

The proxy mode contains the following roles:
Abstract theme Role (Subject): Defines the realsubject and proxy common interfaces so that proxies can be used wherever realsubject is used.
True Theme Role (Realsubject): Defines the real entity represented by proxy.
Proxy object: Saves a reference so that the agent can access the entity and provides an interface that is the same as the Realsubject interface, so that the proxy can be used in place of the entity (Realsubject).

UML diagram:

Code implementation:

<?PHPHeader("content-type:text/html; Charset=utf-8 ");//define what Realsubject and proxy have in commonInterfacesubject{functionsay (); functionrun ();}classRealsubjectImplementssubject{Private $name; function__construct ($name){        $this->name =$name; }    functionsay () {Echo $this->name. " At dinner <br> "; }    functionrun () {Echo $this->name. " In running <br> "; }}classProxyImplementssubject{Private $realSubject=NULL; function__construct (Realsubject$realSubject=NULL){        if(Empty($realSubject)){            $this->realsubject =NewRealsubject (); }Else{            $this->realsubject =$realSubject; }    }    functionsay () {$this->realsubject->say (); }    functionrun () {$this->realsubject->run (); }}//Test$subject=NewRealsubject ("Zhang San");$proxy=NewProxy ($subject);$proxy-say ();$proxy-run ();/*Zhang San is eating, Zhang San is running .*/?>

Advantages:
The proxy mode can coordinate the caller and the callee, and reduce the coupling degree of the system to some extent.
Remote agents enable clients to access objects on remote machines, and remote machines may have better computational performance and processing speed, and can quickly respond to and process client requests.
Virtual agents represent a large object by using a small object, which can reduce the consumption of system resources, optimize the system and improve the speed of operation.
The protection agent can control access to real objects.

Disadvantages:
Because proxy objects are added between the client and the real topic, some types of proxy patterns can cause requests to be processed more slowly.
Implementing the proxy mode requires additional work, and some proxy patterns are very complex to implement.

Applicable scenario:
Depending on the purpose of the proxy mode, there are several common types of proxy modes:
1, Remote proxy: Provides a local proxy object for an object in a different address space, which can be in the same host, or In another host, the remote agent is also called Ambassador (Ambassador).
2, Virtual proxy: If you need to create an object that consumes a large resource, create an object that consumes relatively little, and the real object is created only when it is needed.
3, Copy-on-write proxy: It is a virtual proxy, the replication (cloning) operation is deferred until the client is really needed to execute. In general, a deep clone of an object is a costly operation, and the Copy-on-write agent can delay the operation and be cloned only when the object is used.
4, protection (Protect or access) Proxy: Controls access to an object that can provide different levels of usage rights to different users.
5, buffer (cache) Proxy: Provides temporary storage space for the results of a target operation so that multiple clients can share the results.
6, Firewall (Firewall) Proxy: Protects the target from being approached by a malicious user.
7, Synchronization (synchronization) Proxy: Enables several users to use one object at the same time without conflict.
8, Smart Reference Proxy: provides some extra action when an object is referenced, such as recording the number of times this object is called.


Several commonly used proxy modes:
1, Image proxy: A very common application example of proxy mode is the control of large map browsing.
When a user accesses a Web page through a browser, it does not load a real large image, but instead uses a proxy object to process it, and in the proxy object's method, a thread is used to load a small picture into the client browser, and then a second thread is used in the background to load the large picture into the client. When you need to browse a large picture, the big picture is displayed in the new page. If the user is not finished loading work while browsing the larger map, you can start a thread to display the corresponding prompt. Through the agent technology combined with multi-threaded programming to put the real picture loading into the background to operate, does not affect the foreground picture browsing.
2, remote agent: Remote agent can hide the details of the network, so that the client does not have to consider the existence of the network. The client can fully assume that the remote business object being proxied is local rather than remote, and that the remote proxy object undertakes most of the network communication work.
3, Virtual Agent: When the loading of an object is very resource-intensive, the advantages of virtual agent is very clearly reflected. Virtual proxy mode is a memory-saving technique that takes a lot of memory or handles complex objects that are deferred until they are used.
When the application starts, the proxy object can be used instead of the real object initialization, saving the memory footprint and greatly accelerating the system startup time.
4, dynamic Agent: Dynamic agent is a more advanced proxy mode, its typical application is spring AOP.
In the traditional proxy mode, the client invokes the request () method of the Realsubject class through proxy and also encapsulates other methods (such as Prerequest () and Postrequest ()) in the proxy class to handle some other problems.
If you use proxy mode in this way, the real theme role must be pre-existing and used as the internal member property of the proxy object. If a real-world theme role must correspond to a proxy theme role, which will result in a sharp increase in the number of classes in the system, there is a need to find ways to reduce the number of classes in the system, and how to use the proxy theme role without knowing the real topic role beforehand, which is a problem that dynamic agents need to solve.

Another example:

GitHub Address: Https://github.com/ZQCard/design_pattern

/* * * In proxy mode, we create an object with an existing object to provide a functional interface to the outside world. *  */

(1) Image.class.php (interface)

<? phpnamespace Proxy; Interface image{    publicfunction  display ();}

(2) RealImage.class.php

<?phpnamespace Proxy;classRealimageImplementsimage{Private $fileName;  Public function__construct ($fileName)    {        $this->filename =$fileName; $this->loadfromdisk ($fileName); }     Public functiondisplay () {Print_r("Displaying".$this-fileName); Echo' <pre/> '; }    Private functionLoadfromdisk ($fileName)    {        Print_r("Loading".$fileName); Echo' <pre/> '; }}

(3) ProxyImage.class.php (proxy class)

<?phpnamespace Proxy;classProxyimageImplementsimage{Private $realImage; Private $fileName;  Public function__construct ($fileName)    {        $this->filename =$fileName; }     Public functiondisplay () {if($this->realimage = =NULL){            $this->realimage =NewRealimage ($this-fileName); }        return $this->realimage->display (); }}

(4) proxy.php

<?Phpspl_autoload_register (function($className){    $className=Str_replace(‘\\‘,‘/‘,$className); include $className.". Class.php ";}); UseProxy\proxyimage;$image=NewProxyimage (' a.jpg ');//images are loaded from disk$image-display ();

Proxy mode and PHP implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.