Home > Backend Development > PHP Tutorial > How to implement proxy mode in php

How to implement proxy mode in php

不言
Release: 2023-04-02 13:36:02
Original
4418 people have browsed it

This article mainly introduces the method of implementing proxy mode in PHP, which has certain reference value. Now I share it with you. Friends in need can refer to it

Proxy Pattern:

Provide a proxy for an object, and the proxy object controls the reference to the original object. The proxy pattern is called Proxy or Surrogate in English. It is an object structural pattern.

Pattern motivation:
In some cases, a client does not want or cannot directly reference an object. At this time, it can pass an A third party called a "proxy" is used to implement indirect references. The proxy object can play an intermediary role between the client and the target object, and can remove content and services that the client cannot see or add additional services that the client needs through the proxy object.
By introducing a new object (such as a small picture and a remote proxy object) to operate the real object or using the new object as a substitute for the real object, this implementation mechanism is the proxy mode. By introducing the proxy object To access an object indirectly, this is the pattern motivation of the proxy pattern.

The proxy mode includes the following roles:
Abstract subject role (Subject): defines the public interfaces of RealSubject and Proxy, so that Proxy can be used wherever RealSubject is used.
Real Subject Role (RealSubject): Defines the real entity represented by Proxy.
Proxy object (Proxy): Saves a reference so that the proxy can access the entity, and provides an interface the same as the RealSubject interface, so that the proxy can be used instead of the entity (RealSubject).

UML diagram:

Code implementation:

<?php
header("Content-type:text/html;Charset=utf-8");//定义RealSubject和Proxy共同具备的东西
interface Subject{    
function say();    
function run();
}
class RealSubject implements Subject{    
private $name;    
function __construct($name){        
$this->name = $name;
    }    function say(){        
    echo $this->name."在吃饭<br>";
    }    function run(){        
    echo $this->name."在跑步<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();
    }
}//测试
$subject = new RealSubject("张三");
$proxy = new Proxy($subject);$proxy->say();
$proxy->run();
/*张三在吃饭
张三在跑步*/
?>
Copy after login

Advantages:
The proxy mode can coordinate the caller and the callee, reducing the coupling of the system to a certain extent.
The remote proxy allows the client to access objects on the remote machine. The remote machine may have better computing performance and processing speed, and can quickly respond to and process client requests.
By using a small object to represent a large object, the virtual agent can reduce the consumption of system resources, optimize the system and increase the running speed.
 Protection agents can control access to real objects.

Disadvantages:
Due to the addition of a proxy object between the client and the real topic, some types of proxy modes may cause the processing speed of requests to slow down.
Implementing the proxy mode requires additional work, and the implementation of some proxy modes is very complex.

Applicable scenarios:
According to the purpose of using the proxy mode, common proxy modes have the following types:
1. Remote (Remote) proxy: Provides services for an object located in a different address space A local proxy object. This different address space can be in the same host or another host. The remote proxy is also called an Ambassador.
 2. Virtual proxy: If you need to create an object that consumes a large amount of resources, first create an object that consumes a relatively small amount of resources to represent it. The real object will only be created when needed.
 3. Copy-on-Write agent: It is a type of virtual agent that delays the copy (clone) operation until it is executed only when the client really needs it. Generally speaking, deep cloning of an object is an expensive operation. The Copy-on-Write proxy can delay this operation and the object will only be cloned when it is used.
 4. Protection (Protect or Access) agent: Controls access to an object and can provide different levels of usage permissions to different users.
 5. Cache agent: Provides temporary storage space for the results of a certain target operation so that multiple clients can share these results.
6. Firewall agent: Protect the target from malicious users.
 7. Synchronization agent: enables several users to use an object at the same time without conflict.
 8. Smart Reference Agent: When an object is referenced, it provides some additional operations, such as recording the number of times the object is called, etc.

几种常用的代理模式:
  1、图片代理:一个很常见的代理模式的应用实例就是对大图浏览的控制。
  用户通过浏览器访问网页时先不加载真实的大图,而是通过代理对象的方法来进行处理,在代理对象的方法中,先使用一个线程向客户端浏览器加载一个小图片,然后在后台使用另一个线程来调用大图片的加载方法将大图片加载到客户端。当需要浏览大图片时,再将大图片在新网页中显示。如果用户在浏览大图时加载工作还没有完成,可以再启动一个线程来显示相应的提示信息。通过代理技术结合多线程编程将真实图片的加载放到后台来操作,不影响前台图片的浏览。
  2、远程代理:远程代理可以将网络的细节隐藏起来,使得客户端不必考虑网络的存在。客户完全可以认为被代理的远程业务对象是局域的而不是远程的,而远程代理对象承担了大部分的网络通信工作。
  3、虚拟代理:当一个对象的加载十分耗费资源的时候,虚拟代理的优势就非常明显地体现出来了。虚拟代理模式是一种内存节省技术,那些占用大量内存或处理复杂的对象将推迟到使用它的时候才创建。
  在应用程序启动的时候,可以用代理对象代替真实对象初始化,节省了内存的占用,并大大加速了系统的启动时间。
  4、动态代理:动态代理是一种较为高级的代理模式,它的典型应用就是Spring AOP。
  在传统的代理模式中,客户端通过Proxy调用RealSubject类的request()方法,同时还在代理类中封装了其他方法(如preRequest()和postRequest()),可以处理一些其他问题。
  如果按照这种方法使用代理模式,那么真实主题角色必须是事先已经存在的,并将其作为代理对象的内部成员属性。如果一个真实主题角色必须对应一个代理主题角色,这将导致系统中的类个数急剧增加,因此需要想办法减少系统中类的个数,此外,如何在事先不知道真实主题角色的情况下使用代理主题角色,这都是动态代理需要解决的问题。

另一个例子:

设计模式之代理模式(php实现)

github地址:https://github.com/ZQCard/design_pattern

/**
 * 在代理模式中,我们创建具有现有对象的对象,以便向外界提供功能接口。
 *  1、Windows 里面的快捷方式。
 * 2、猪八戒去找高翠兰结果是孙悟空变的,可以这样理解:把高翠兰的外貌抽象出来,高翠兰本人和孙悟空都实现了这个接口,
 * 猪八戒访问高翠兰的时候看不出来这个是孙悟空,所以说孙悟空是高翠兰代理类。
 * 3、买火车票不一定在火车站买,也可以去代售点。
 * 4、一张支票或银行存单是账户中资金的代理。支票在市场交易中用来代替现金,并提供对签发人账号上资金的控制。
 *优点:
 * 1、职责清晰。 2、高扩展性。 3、智能化。
 * 缺点:
 * 1、由于在客户端和真实主题之间增加了代理对象,因此有些类型的代理模式可能会造成请求的处理速度变慢。
 * 2、实现代理模式需要额外的工作,有些代理模式的实现非常复杂。
 * 例子:从服务器读取一张图片的时候,第一次从硬盘读取,将资源对象代理,第二次读取的时候就使用代理对象去读取。 */
Copy after login

(1)Image.class.php(接口)

<?php

namespace Proxy;interface Image
{    public function display();
}
Copy after login

(2)RealImage.class.php

<?php

namespace 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 &#39;<pre/>&#39;;
    }    private function loadFromDisk($fileName)
    {        print_r("Loading ". $fileName);        echo &#39;<pre/>&#39;;
    }
}
Copy after login

(3)ProxyImage.class.php(代理类)

<?php

namespace 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();
    }
}
Copy after login

(4)proxy.php

<? ( = (&#39;\\&#39;,&#39;/&#39;, .".class.php" =  ProxyImage(&#39;a.jpg&#39;->
Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

PHP中的操作mysqli的预处理prepare

单例模式连接数据库的方法

The above is the detailed content of How to implement proxy mode in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template