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();$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().
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!

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc


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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version
SublimeText3 Linux latest version
