How to implement proxy mode in PHP

Source: Internet
Author: User
This article mainly introduces the PHP implementation of proxy mode, has a certain reference value, and now share to everyone, the need for friends can refer to

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 common interface subject{function say (); function run ();}    Class Realsubject implements subject{private $name;    function __construct ($name) {$this->name = $name; } function say () {echo $this->name. "    At dinner <br> "; } function run () {echo $this->name.    In running <br> ";    }}class Proxy implements subject{private $realSubject = null; function __construct (realsubject $realSubject = null) {if (empty ($realSubject)) {$this->realsubject =        New Realsubject ();        }else{$this->realsubject = $realSubject;    }} function Say () {$this->realsubject->say ();    } function Run () {$this->realsubject->run (); }}//Test $subject = new Realsubject ("Zhang San"), $proxy = new Proxy ($subject); $proxy->say (); $proxy->run ();/* Zhang San eating zhang San 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 scenarios:
Depending on the purpose of the proxy mode, there are several types of common proxy modes:
1. Remote agent: Provide a local proxy object for an object in a different address space, the different address space can be in the same host, but also 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 Agent: It is a virtual agent, the replication (cloning) operation is deferred to only when the client really needs 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, protect (Protect or access) Proxy: Control access to an object, you can provide different users with different levels of access.
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) Agent: Protect the target not to let malicious users close.
7. Synchronous (synchronization) Proxy: Enables several users to use one object at the same time without conflict.
8, Smart Reference Proxy: When an object is referenced, provide some extra action, such as the number of times this object is called to log down and so on.

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:

Proxy mode of design mode (PHP implementation)

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, Windows inside the shortcut. * 2, Pig Eight quit to find Miss Gao Cuilan The result is the Monkey King change, can understand: the appearance of Miss Gao Cuilan abstract out, Miss Gao Cuilan himself and the Monkey King have realized this interface, * Pig visit Miss Gao Cuilan when not to see this is the Monkey king, so said the Monkey King is Miss Gao Cuilan proxy class. * 3, Buy train tickets not necessarily at the railway station to buy, you can also go to the consignment point. * 4. A cheque or bank deposit is an agent of the funds in the account. Cheques are used to replace cash in market transactions and to provide control over the funds on the issuer's account. * Advantages: * 1, clear responsibilities. 2, high scalability. 3, intelligent. * Cons: * 1, due to the addition of proxy objects between the client and the real topic, some types of proxy modes may cause the request to be processed more slowly. * 2, the implementation of Proxy mode requires additional work, some of the implementation of proxy mode is very complex. * Example: When reading a picture from the server, the first time to read from the hard disk, the resource object agent, the second time to read the use of proxy object to read. */

(1) Image.class.php (interface)

<?phpnamespace proxy;interface image{public    function display ();

(2) RealImage.class.php

<?phpnamespace Proxy;class Realimage implements image{    private $fileName;    Public function __construct ($fileName)    {        $this->filename = $fileName;        $this->loadfromdisk ($fileName);    }    Public function display ()    {        print_r ("Displaying"). $this->filename);        Echo ' <pre/> ';    }    Private Function Loadfromdisk ($fileName)    {        print_r ("Loading"). $fileName);        Echo ' <pre/> ';    }}

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

<?phpnamespace Proxy;class Proxyimage implements image{    private $realImage;    Private $fileName;    Public function __construct ($fileName)    {        $this->filename = $fileName;    }    Public function display ()    {        if ($this->realimage = = null) {                $this->realimage = new Realimage ($this- >filename);        }        return $this->realimage->display ();}    }

(4) proxy.php

<? ( = ('\\','/', .". class.php "=  proxyimage (' a.jpg ')

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

Related Article

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.