This article mainly uses example code to introduce PHP proxy mode in detail.
In the previous article, we have given you a brief introduction to the basic concepts of PHP proxy mode. I believe everyone also has a little understanding of the proxy mode.
This section will introduce you to PHP proxy mode based on specific code examples.
The code is as follows:
<?php /* * 代理模式 */ //代理抽象接口 interface shop { public function buy($title); } //原来的CD商店,被代理对象 class CDShop implements shop { public function buy($title) { echo "购买成功,这是你的《{$title}》唱片" . PHP_EOL; } } //CD代理 class Proxy implements shop { public function buy($title) { $this->go(); $CDshop = new CDshop; $CDshop->buy($title); } public function go() { echo "跑去香港代购" . PHP_EOL; } } class client { public static function shoping($goods) { $proxy = new Proxy; $proxy->buy($goods); } } client::shoping("醒着做梦");
First of all, the proxy mode needs to inherit a common interface. There are only two classes: CDShop (CD store) and Proxy (CD proxy). To inherit a common interface shop, and all of them have a common method buy.
Then we can understand the above code in this way. When we want to buy a "Waking and Dreaming" record, but because there are no local resources, we can only choose a Hong Kong agent to help purchase it. Here we can instantiate the proxy Proxy through the client, and then call the purchase method buy in the proxy.
Then the agent can use the go method to express "go to Hong Kong to purchase", then new instantiate CDshop, and then use the buy method to "buy records".
Finally we can check the return value of the above code:
Process diagram:
##As shown in the figure, this is an example of using the proxy mode. As long as you master its implementation process and principles, it is easy to understand the implementation ideas of the proxy mode. You can also do more exercises locally to strengthen your understanding. This article is a detailed introduction to the PHP proxy mode. It is also very easy to understand. I hope it will be helpful to friends in need!The above is the detailed content of How to understand PHP proxy mode. For more information, please follow other related articles on the PHP Chinese website!