Table of Contents
Design patterns in Symfony2 - Decorator pattern, symfony2 design pattern
Home Backend Development PHP Tutorial Design patterns in Symfony2 - Decorator pattern, symfony2 design pattern_PHP tutorial

Design patterns in Symfony2 - Decorator pattern, symfony2 design pattern_PHP tutorial

Jul 13, 2016 am 10:12 AM
Design thinking

Design patterns in Symfony2 - Decorator pattern, symfony2 design pattern

Definition of decorator pattern

Dynamically extend the functionality of an object without changing the original class file and using inheritance. It wraps the real object by creating a wrapping object, that is, decoration.

The decorator pattern puts each function to be decorated in a separate class, and lets this class wrap the object it wants to decorate. Therefore, when special behavior needs to be performed, the client code can run according to It is necessary to use decoration functions to wrap objects selectively and sequentially.

Design patterns in Symfony2 - Decorator pattern, symfony2 design pattern_PHP tutorialPicture 1

Usage scenarios

Imagine if we need to create a student with different clothes for different occasions, for example: students at school need to wear school uniforms, students at dances need to wear formal clothes, and students at home can dress naked (a bit perverted) , of course, you can also learn from Superman to wear his underwear outside. At this point the question arises, do we need to write a student class dressed differently for each occasion? What if our kid wants someone wearing school uniform pants and a formal top with exposed bottoms? StudentWithSchoolUniform, StudentWithFormalWear, StudentWithNaked, StudentWithSchoolUniformAndOutSideUnderWear......... Endless classes~~~ Tired! Yes, if this causes an explosion of classes, and as demand increases, classes will continue to increase, and the maintenance difficulty of the entire system can be imagined.

So at this time, the decorator mode can play its role. Underwear, formal wear, school uniforms, shoes, glasses, etc. are all specific decorators. Students are the specific objects to be decorated. The decorated object and the abstract class of the decorator both inherit the same parent class. Wearing different clothes for students is actually using the decorator class (clothing) to wrap the decorated class (students). To put it figuratively, this is a dressing process.

Classes and Interfaces

  • Component (base class of the decorated object, corresponding to the Person class of the example)
  • ConcreteComponent (specific decorated object, corresponding to the Student class of the example)
  • Decorator (decorator base class, Costume corresponding to the example)
  • ContreteDecorator (specific decorator class, corresponding to examples of Pants, Shirt, etc.)

Example

Design patterns in Symfony2 - Decorator pattern, symfony2 design pattern_PHP tutorialPicture 2

Person.php

Design patterns in Symfony2 - Decorator pattern, symfony2 design pattern_PHP tutorial 1 php 2 3 /** 4 * Person.php 5 * Decorated base class 6 **/ 7 abstract class Person{ 8 9 public abstract function show(); 10 11 } View Code

Student.php

Design patterns in Symfony2 - Decorator pattern, symfony2 design pattern_PHP tutorial 1 php 2 3 /** 4 * Student.php 5 * Specific decorated object 6 **/ 7 class Student extends Person{ 8 9 private $name; 10 11 public function __construct($name){ 12 $this->name = $name; 13 } 14 15 public function show(){ 16 echo 'I am a student',$this->name; 17 } 18 } View Code

Costume.php

Design patterns in Symfony2 - Decorator pattern, symfony2 design pattern_PHP tutorial 1 php 2 3 /** 4 * Costume.php 5 * Decorator base class 6 **/ 7 abstract class Costume extends Person{ 8 9 10 } View Code

Shirt.php

Design patterns in Symfony2 - Decorator pattern, symfony2 design pattern_PHP tutorial 1 php 2 3 /** 4 * Shirt.php 5 * Specific decorator class 6 **/ 7 class Shirt extends Costume{ 8 9 private $person; 10 11 public function __construct(Person $person){ 12 13 $this->person = $person; 14 15 } 16 17 public function show(){ 18 19 echo $this->person->show(),',wearing shirt'; 20 } 21 22 } View Code

Pants.php

Design patterns in Symfony2 - Decorator pattern, symfony2 design pattern_PHP tutorial 1 php 2 3 /** 4 * Pants.php 5 **/ 6 class Pants extends Costume{ 7 8 private $person; 9 10 public function __construct(Person $person){ 11 12 $this->person = $person; 13 14 } 15 16 public function show(){ 17 18 echo $this->person->show(),',wearing pants'; 19 } 20 21 } View Code

Glasses.php

Design patterns in Symfony2 - Decorator pattern, symfony2 design pattern_PHP tutorial 1 php 2 3 /** 4 * Glasses.php 5 **/ 6 class Glasses extends Costume{ 7 8 private $person; 9 10 public function __construct(Person $person){ 11 12 $this->person = $person; 13 14 } 15 16 public function show(){ 17 18 echo $this->person->show(),',with glasses'; 19 } 20 21 } View Code

UnderWear.php

Design patterns in Symfony2 - Decorator pattern, symfony2 design pattern_PHP tutorial 1 php 2 3 /** 4 * UnderWear.php 5 **/ 6 class UnderWear extends Costume{ 7 8 private $person; 9 10 public function __construct(Person $person){ 11 12 $this->person = $person; 13 14 } 15 16 public function show(){ 17 18 echo $this->person->show(),',穿着DK'; 19 } 20 21 } View Code

Client.php

<span> 1</span> <?<span>php
</span><span> 2</span> 
<span> 3</span>     <span>require_once</span> 'Person.php'<span>;
</span><span> 4</span>     <span>require_once</span> 'Costume.php'<span>;
</span><span> 5</span>     <span>require_once</span> 'Student.php'<span>;
</span><span> 6</span>     <span>require_once</span> 'UnderWear.php'<span>;
</span><span> 7</span>     <span>require_once</span> 'Shirt.php'<span>;
</span><span> 8</span>     <span>require_once</span> 'Pants.php'<span>;
</span><span> 9</span>     <span>require_once</span> 'Glasses.php'<span>;
</span><span>10</span> 
<span>11</span>     <span>//</span><span> Student继承Person</span>
<span>12</span>     <span>$jc</span> = <span>new</span> Student('JC'<span>);
</span><span>13</span>     <span>$jc</span>->show();   <span>//</span><span> 我是学生JC</span>
<span>14</span>     <span>echo</span> '<br>'<span>;
</span><span>15</span> 
<span>16</span>     <span>//</span><span> 用UnderWear类装饰Person</span>
<span>17</span>     <span>$underwear</span> = <span>new</span> UnderWear(<span>$jc</span><span>);
</span><span>18</span>     <span>$underwear</span>->show();  <span>//</span><span> 我是学生JC,穿着DK</span>
<span>19</span>     <span>echo</span> '<br>'<span>;
</span><span>20</span> 
<span>21</span>     <span>//</span><span> 再用Pants类装饰Person</span>
<span>22</span>     <span>$pants</span> = <span>new</span> Pants(<span>$underwear</span><span>);
</span><span>23</span>     <span>$pants</span>->show();   <span>//</span><span> 我是学生JC,穿着DK,穿着裤子</span>
<span>24</span>     <span>echo</span> '<br>'<span>;
</span><span>25</span> 
<span>26</span>     <span>//</span><span> 再用Shirt类装饰Person</span>
<span>27</span>     <span>$shirt</span> = <span>new</span> Shirt(<span>$pants</span><span>);
</span><span>28</span>     <span>$shirt</span>->show();  <span>//</span><span> 我是学生JC,穿着DK,穿着裤子,穿着衬衫</span>
<span>29</span>     <span>echo</span> '<br>'<span>;
</span><span>30</span> 
<span>31</span>     <span>//</span><span> 再用Glasses类装饰Person</span>
<span>32</span>     <span>$glasses</span> = <span>new</span> Glasses(<span>$shirt</span><span>);
</span><span>33</span>     <span>$glasses</span>->show();  <span>//</span><span> 我是学生JC,穿着DK,穿着裤子,穿着衬衫,带着眼镜</span>
<span>34</span>     <span>echo</span> '<br>';
Copy after login

Design patterns in Symfony2 - Decorator pattern, symfony2 design pattern_PHP tutorial图3 输出结果截图

Symfony2 EventDispatch 组件对装饰者模式的应用

 Design patterns in Symfony2 - Decorator pattern, symfony2 design pattern_PHP tutorial图4 Symfony2 EventDispatch组件使用装饰模式

图5 Framework配置EventDispatcher

 

  • SymfonyComponentEventDispatcherEventDispatcherInterface 是被装饰的接口
  • SymfonyComponentEventDispatcherEventDispatcher 和 SymfonyComponentEventDispatcherContainerAwareEventDispatcher 是被装饰的具体对象
  • SymfonyComponentEventDispatcherDebugTraceableEventDispatcherInterface 装饰者接口
  • SymfonyComponentEventDispatcherDebugTraceableEventDispatcher 装饰者基类
  • SymfonyComponentHttpKernelDebugTraceableEventDispatcher 具体的装饰者对象

  具体装饰者对象SymfonyComponentHttpKernelDebugTraceableEventDispatcher::dispatch()方法,核心依旧是调用被装饰的具体对象SymfonyComponentEventDispatcherEventDispatcher::dispatch()方法进行工作,但是装饰者对象SymfonyComponentHttpKernelDebugTraceableEventDispatcher::dispatch()方法添加了相应的功能,例如在调用SymfonyComponentEventDispatcherEventDispatcher::dispatch()方法前后分别调用了preProcess()、preDispatch()和postDispatch()、postProcess():

<span> 1</span>     <span>/*</span><span>*
</span><span> 2</span> <span>     * {@inheritdoc}
</span><span> 3</span>      <span>*/</span>
<span> 4</span>     <span>public</span> <span>function</span> dispatch(<span>$eventName</span>, Event <span>$event</span> = <span>null</span><span>)
</span><span> 5</span> <span>    {
</span><span> 6</span>         <span>if</span> (<span>null</span> === <span>$event</span><span>) {
</span><span> 7</span>             <span>$event</span> = <span>new</span><span> Event();
</span><span> 8</span> <span>        }
</span><span> 9</span> 
<span>10</span>         <span>//</span><span> 装饰者对象增加的功能</span>
<span>11</span>         <span>$this</span>->preProcess(<span>$eventName</span><span>);
</span><span>12</span>         <span>$this</span>->preDispatch(<span>$eventName</span>, <span>$event</span><span>);
</span><span>13</span> 
<span>14</span>         <span>$e</span> = <span>$this</span>->stopwatch->start(<span>$eventName</span>, 'section'<span>);
</span><span>15</span> 
<span>16</span>         <span>//</span><span> 核心依旧是调用被装饰的具体对象Symfony\Component\EventDispatcher\EventDispatcher::dispatch()方法</span>
<span>17</span>         <span>$this</span>->dispatcher->dispatch(<span>$eventName</span>, <span>$event</span><span>);
</span><span>18</span> 
<span>19</span>         <span>if</span> (<span>$e</span>-><span>isStarted()) {
</span><span>20</span>             <span>$e</span>-><span>stop();
</span><span>21</span> <span>        }
</span><span>22</span> 
<span>23</span>         <span>//</span><span> 装饰者对象增加的功能</span>
<span>24</span>         <span>$this</span>->postDispatch(<span>$eventName</span>, <span>$event</span><span>);
</span><span>25</span>         <span>$this</span>->postProcess(<span>$eventName</span><span>);
</span><span>26</span> 
<span>27</span>         <span>return</span> <span>$event</span><span>;
</span><span>28</span>     }
Copy after login

 

优点

缺点

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/918062.htmlTechArticleSymfony2中的设计模式——装饰者模式,symfony2设计模式 装饰者模式的定义 在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的...
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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

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.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

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.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

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: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

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.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

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.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO) How do you prevent SQL Injection in PHP? (Prepared statements, PDO) Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

See all articles