Home Backend Development PHP Tutorial Implementation of multi-level cache---chain of responsibility model

Implementation of multi-level cache---chain of responsibility model

Jul 25, 2016 am 09:06 AM

Multi-level caching chain of responsibility model.
* The client submits it to the handler, and the handler finds a function in the chain of responsibility that can handle the task and processes it; it can be summarized as: using a series of classes to try to handle a request. There is a loose coupling between these classes, and the only thing they have in common is The point is to pass the request between them. In other words, when a request comes, Class A will handle it first. If it is not processed, it will be passed to Class B for processing. If it is not processed, it will be passed to Class C for processing. It is like a chain. (chain) is passed on.
  1. /**
  2. * Chain of Responsibility pattern, its purpose is to organize an object chain to handle a request such as a method call.
  3. *
  4. * The most famous example of chain of responsibility: multi-level caching.
  5. * The client submits it to the handler, and the handler finds a function in the chain of responsibility that can handle the task and processes it;
  6. * It can be summarized as: using a series of classes to try to handle a request, and there is a loose coupling between these classes.
  7. * The only thing they have in common is that requests are passed between them. In other words, when a request comes, Class A will handle it first. If it is not processed,
  8. * will be passed to Class B for processing. If it is not processed, it will be passed to Class C for processing. , and it is passed on like a chain.
  9. */
  10. /**
  11. * The Handler abstraction. Objects that want to be a part of the
  12. * ChainOfResponsibility must implement this interface directly or via
  13. * inheritance from an AbstractHandler.
  14. * Interface or
  15. * inherit an abstract processing class
  16. */
  17. interface KeyValueStore{
  18. /**
  19. * Obtain a value.
  20. * @param string $key
  21. * @return mixed
  22. */
  23. public function get($key);
  24. }
  25. /**
  26. * Basic no-op implementation which ConcreteHandlers not interested in
  27. * caching or in interfering with the retrieval inherit from.
  28. * Receives a request, tries to satisfy it, and delegates to the next handler if unsuccessful.
  29. */
  30. abstract class AbstractKeyValueStore implements KeyValueStore{
  31. protected $_nextHandler;
  32. public function get($key){
  33. return $this->_nextHandler->get($key);
  34. }
  35. }
  36. /**
  37. * Ideally the last ConcreteHandler in the chain. At least, if inserted in
  38. * a Chain it will be the last node to be called.
  39. * Ideally, the last concrete processing class on the responsibility chain is added to the chain and will is the last node called.
  40. */
  41. class SlowStore implements KeyValueStore{
  42. /**
  43. * This could be a somewhat slow store: a database or a flat file.
  44. */
  45. protected $_values;
  46. public function __construct(array $values = array()){
  47. $this->_values = $values;
  48. }
  49. public function get($key){
  50. return $this->_values[$key];
  51. }
  52. }
  53. /**
  54. * A ConcreteHandler that handles the request for a key by looking for it in
  55. * its own cache. Forwards to the next handler in case of cache miss.
  56. * In case of cache miss, forward to the next processing object
  57. */
  58. class InMemoryKeyValueStore implements KeyValueStore{
  59. protected $_nextHandler;
  60. protected $_cached = array();
  61. public function __construct(KeyValueStore $nextHandler){
  62. $this->_nextHandler = $nextHandler;
  63. }
  64. protected function _load($key){
  65. if (!isset($this->_cached[$key])) {
  66. $this->_cached[$key] = $this->_nextHandler->get($key);
  67. }
  68. }
  69. public function get($key){
  70. $this->_load($key);
  71. return $this->_cached[$key];
  72. }
  73. }
  74. /**
  75. * A ConcreteHandler that delegates the request without trying to
  76. * understand it at all. It may be easier to use in the user interface
  77. * because it can specialize itself by defining methods that generates
  78. * html, or by addressing similar user interface concerns.
  79. * Some Clients see this object only as an instance of KeyValueStore
  80. * and do not care how it satisfy their requests, while other ones
  81. * may use it in its entirety (similar to a class-based adapter).
  82. * No client knows that a chain of Handlers exists.
  83. * 不用关心调用的具体实现的外部具体具体处理程序;背后是责任链。
  84. */
  85. class FrontEnd extends AbstractKeyValueStore{
  86. public function __construct(KeyValueStore $nextHandler){
  87. $this->_nextHandler = $nextHandler;
  88. }
  89. public function getEscaped($key){
  90. return htmlentities($this->get($key), ENT_NOQUOTES, 'UTF-8');
  91. }
  92. }
  93. // Client code
  94. $store = new SlowStore(
  95. array(
  96. 'pd' => 'Philip K. Dick',
  97. 'ia' => 'Isaac Asimov',
  98. 'ac' => 'Arthur C. Clarke',
  99. 'hh' => 'Helmut Hei.enbttel'
  100. )
  101. );
  102. // in development, we skip cache and pass $store directly to FrontEnd
  103. $cache = new InMemoryKeyValueStore($store);
  104. $frontEnd = new FrontEnd($cache);
  105. echo $frontEnd->get('ia'). "n";
  106. echo $frontEnd->getEscaped('hh'). "n";
  107. /**
  108. * expect: ...
  109. * Isaac Asimov
  110. * Helmut Hei.enbttel
  111. *
  112. * Participants:
  113. ◆Client (client): Submit a request to Handler (handler);
  114. ◆Handler (handler) Abstract: Receive a request, satisfy it in some way;
  115. ◆ConcreteHandlers (concrete handlers): Receive a request, try to satisfy it, and delegate to the next handler if unsuccessful.
  116. */
复制代码


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1254
29
C# Tutorial
1228
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

What is the difference between include, require, include_once, require_once? What is the difference between include, require, include_once, require_once? Apr 05, 2025 am 12:07 AM

In PHP, the difference between include, require, include_once, require_once is: 1) include generates a warning and continues to execute, 2) require generates a fatal error and stops execution, 3) include_once and require_once prevent repeated inclusions. The choice of these functions depends on the importance of the file and whether it is necessary to prevent duplicate inclusion. Rational use can improve the readability and maintainability of the code.

Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles