Home  >  Article  >  Backend Development  >  PHP design ideas: proxy mode and practice of separation of reading and writing

PHP design ideas: proxy mode and practice of separation of reading and writing

*文
*文Original
2017-12-25 10:05:321581browse

There are many excellent pattern design ideas in programming. This article uses the proxy pattern to achieve separation of reading and writing, so that everyone can have a certain understanding of the proxy pattern.

I believe many students are familiar with the word agency!

1. From a non-program perspective, the most common thing in an agent’s life is the various products that pop up in the circle of friends, etc.

2. From the perspective of server architecture, a proxy is a forwarder. It is like you need to communicate with a third party, but you cannot communicate with him directly. You have to rely on others to help you with the message. This kind of middleman It’s an agent!

3. From the design mode, it is similar to the above two, that is, it is equivalent to middleware, and then obtains data from the agent through rpc


First we Let’s sort out the steps for using the proxy mode to separate reading and writing

1) The interface class must be (unified and standardized)

First we have to define an interface file

interface IProxy
{
function getThing($id);
function setThing($id, $name);
}

This is done The purpose is to unify planning and follow object-oriented programming specifications!

"PHP Object-Oriented Programming Specification"

2) Implement the interface method

class Proxy implements IProxy
{
//如果是读操作就用连接从数据库
public function getThing($id)
{
$db = Factory::getDatabase('slave'); //工厂模式封装(后面讲)
$db->query("select name from user where id =$id limit 1");
}
//如果是写操作就连接主数据库
public function setThing($id, $name)
{
    $db = Factory::getDatabase('master');  //工厂模式封装(后面讲)
    $db->query("update user set name = $name where id =$id limit 1");
}
}

In this way, the data reading and writing separation operation of the proxy mode is simply realized! Of course, this is just an operation on one model. Friends can encapsulate multiple models by themselves, as long as they strictly follow the object-oriented programming specifications!


Related recommendations:

Detailed Explanation of the Adapter Pattern of PHP Design Pattern

Detailed Explanation of the Iterator Pattern of PHP Design Pattern

##Detailed Explanation of the Decorator Pattern of PHP Design Pattern

The above is the detailed content of PHP design ideas: proxy mode and practice of separation of reading and writing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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