


Detailed explanation of the use of PHP template method pattern
This time I will bring you a detailed explanation of the use of PHP template method mode. What are the precautions when using PHP template method mode. The following is a practical case, let's take a look.
What is the template method pattern
Template MethodDesign pattern A class method templateMethod() is used, which is a concrete method in an abstract class. The function of this method is to sort the sequence of abstract methods, and the specific implementation is left to the concrete class. The key is that the template method pattern defines the algorithm in the operation. The "skeleton" is implemented by concrete classes.
When to use template methods
If some steps in the algorithm have been clarified, However, these steps can be implemented in many different ways, and you can use the template method to debug. If the steps in the algorithm remain unchanged, you can leave these steps to the subclass for specific implementation. In this case, you can use the template method to design the pattern. To organize the basic operations (functions/methods) in the abstract class. Then the subclasses implement these operations required by the application.
There is also a slightly more complicated usage, which may need to put the common behaviors of the subclasses into In a class to avoid code duplication.
If you use multiple classes to solve the same large problem, duplicate code may quickly appear.
One more thing, you can use templates The method pattern controls subclass expansion, which is the so-called "hook".
Example
In PHP programming, you may often encounter a problem: To establish a band Image of the picture title. This algorithm is quite simple, it is to display the image, and then display the text below the image.
Since only two participants are involved in the template design, this is one of the easiest patterns to understand, and at the same time Also very useful. Abstractly create templateMethod()
, and implement this method by a concrete class.
Abstract class
Abstract class is the key here , because it contains both concrete and abstract methods. Template methods are often concrete methods, and their operations are abstract.
The two abstract methods are addPicture and addTitile. Both operations contain a parameter, representing the image respectively. URL information and image title.
Template.php
<?php abstract class Template { protected $picture; protected $title; public function display($pictureNow, $titleNow) { $this->picture = $pictureNow; $this->title = $titleNow; $this->addPicture($this->picture); $this->addTitle($this->title); } abstract protected function addPicture($picture); abstract protected function addTitle($title); }
Concrete Class
##Concrete.php
<?php include_once('Template.php'); class Concrete extends Template { protected function addPicture($picture) { $this->picture = 'picture/' . $picture; echo "图像路径为:" . $this->picture . '<br />'; } protected function addTitle($title) { $this->title = $title; echo "<em>标题: </em>" . $this->title . "<br />"; } }
Customer
Client.php
<?php function autoload($class_name) { include $class_name . '.php'; } class Client { public function construct() { $title = "chenqionghe is a handsome boy"; $concrete = new Concrete(); $concrete->display('chenqionghe.png', $title); } } $worker = new Client();
display().
The image path is: picture/chenqionghe.pngAs you can see, the customer only needs to provide the image address and titleTitle: chenqionghe is a handsome boy
Hooks in Template Method Design Pattern
Sometimes the template method function may have a step that you don’t want. In some specific cases, you may not want to perform this step. In this case, You can use the hook of the template method.In the template method design pattern, you can use hooks to make a method a part of the template, but this method may not necessarily be used. In other words, it is part of the method. , but it contains a hook that can handle exceptions. Subclasses can add an optional element to the algorithm. In this way, although it is still executed in the order established by the template method, it may not complete the actions expected by the template method. For In this optional situation, hooks are the most ideal tool to solve this problem.Example
Go shopping online and get a 20% discount. If the total product cost exceeds 200 Yuan, the 12.95 Yuan shipping fee will be waived.Establishing hooks
It is interesting to establish hook methods in template methods. Although subclasses can change the behavior of hooks, Still have to follow the order defined in the templateIHook.php
<?php abstract class IHook { protected $hook; protected $fullCost; public function templateMethod($fullCost, $hook) { $this->fullCost = $fullCost; $this->hook = $hook; $this->addGoods(); $this->addShippingHook(); $this->displayCost(); } protected abstract function addGoods(); protected abstract function addShippingHook(); protected abstract function displayCost(); }
这里有3个抽象方法: addGoods()
, addShippingHook()
,displayCost()
, 抽象类IHook实现的templateMethod()
中确定了它们的顺序. 在这里, 钩子方法放在中间, 实际上模板方法指定的顺序中, 钩子可以放在任意位置. 模板方法需要两个参数, 一个是总花费, 另外还需要一个变量用来确定顾客是否免收运费.
实现钩子
一旦抽象类中建立了这些抽象方法, 并指定了它们执行的顺序, 子类将实现所有这3个方法:
Concrete.php
<?php class Concrete extends IHook { protected function addGoods() { $this->fullCost = $this->fullCost * 0.8; } protected function addShippingHook() { if(!$this->hook) { $this->fullCost += 12.95; } } protected function displayCost() { echo "您需要支付: " . $this->fullCost . '元<br />'; } }
addGoods和displayCost都是标准方法, 只有一个实现., 不过, addShippingHook的实现有所不同, 其中有一个条件来确定是否增加运费. 这就是钩子.
客户Client
Client.php
<?php function autoload($class_name) { include $class_name . '.php'; } class Client { private $totalCost; private $hook; public function construct($goodsTotal) { $this->totalCost = $goodsTotal; $this->hook = $this->totalCost >= 200; $concrete = new Concrete(); $concrete->templateMethod($this->totalCost, $this->hook); } } $worker = new Client(100); $worker = new Client(200);
该Client演示了分别购买100块钱和200块钱的商品最后的费用,运行结果如下
您需要支付: 92.95元
您需要支付: 160元
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed explanation of the use of PHP template method pattern. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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.

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

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.
