Home Backend Development PHP Tutorial Detailed explanation of the use of PHP template method pattern

Detailed explanation of the use of PHP template method pattern

May 17, 2018 am 11:50 AM
php use Detailed explanation

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

Concrete Class

##Concrete.php

<?php
include_once(&#39;Template.php&#39;);
class Concrete extends Template
{
  protected function addPicture($picture)
  {
    $this->picture = &#39;picture/&#39; . $picture;
    echo "图像路径为:" . $this->picture . &#39;<br />&#39;;
  }
  protected function addTitle($title)
  {
    $this->title = $title;
    echo "<em>标题: </em>" . $this->title . "<br />";
  }
}
Copy after login

Customer

Client.php

<?php
function autoload($class_name)
{
  include $class_name . &#39;.php&#39;;
}
class Client
{
  public function construct()
  {
    $title = "chenqionghe is a handsome boy";
    $concrete = new Concrete();
    $concrete->display(&#39;chenqionghe.png&#39;, $title);
  }
}
$worker = new Client();
Copy after login

$concrete variable instantiates Concrete, but it calls display template method, this is a specific operation inherited from the parent class. The parent class calls the operation of the subclass through

display().

Output after running

The image path is: picture/chenqionghe.png

Title: chenqionghe is a handsome boy

As you can see, the customer only needs to provide the image address and title

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 template

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

这里有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 . &#39;元<br />&#39;;
  }
}
Copy after login

addGoods和displayCost都是标准方法, 只有一个实现., 不过, addShippingHook的实现有所不同, 其中有一个条件来确定是否增加运费. 这就是钩子.

客户Client

Client.php

<?php
function autoload($class_name)
{
  include $class_name . &#39;.php&#39;;
}
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);
Copy after login

该Client演示了分别购买100块钱和200块钱的商品最后的费用,运行结果如下

您需要支付: 92.95元
您需要支付: 160元

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

PHP接口隔离原则(ISP)使用案例解析

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!

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

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,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles