Design Patterns

PHPhường Design patterns have sầu proven to be extremely useful khổng lồ developers và is a major problem solver. To write efficient code, developers must follow best practices. PHP Design patterns is an Object-oriented programming (OOP) concept that is now also used in Drupal 8 projects. With Drupal 8 adopting modern PHPhường và OOP concepts, design patterns can be leveraged for a cleaner & more robust programming.

Bạn đang xem: Design patterns

*

What are Design Patterns in PHP?

In software engineering, a Design Pattern is a general repeatable solution to commonly occurring problem in software Design. Good Object-oriented designs should be reusable, maintainable and extensible and Design Patterns in PHP. could be very helpful in doing that. It does not only help in solving problems, it implies an optimal way addressing common challenges.

Benefits of using PHP Design Patterns

Major benefits of design patterns in PHP are :

PHP Design patters help in solving repetitive sầu problems faced during developmentOther developers looking at your code won’t have to lớn struggle khổng lồ understand as the code is well structured with kiến thiết patternsFollowing best practices helps build more robust softwareIt helps make development faster & easier

Widely used Design Patterns in PHP

Design Patterns can be used in various situations lớn solve similar problems. There are around 23 design patters that can be broadly categorized into lớn three types of design patterns - Creational, Structural & Behavioral patterns.

Creational Patterns: Design patterns that are used in object creation mechanisms, khổng lồ create objects that can be decoupled from the system that implemented them.

Structural Patterns: This eases the kiến thiết by identifying simple ways to lớn realize relationships between entities

Behavioral Patterns: They are used lớn manage relationships, responsibilities, and algorithms between objects

Factory Pattern

A factory pattern is used lớn build an object. That’s right — build an object & not create an object. When we build the object, we first create it & then initialize it. Usually, it requires to apply certain súc tích và perform multiple steps. With that, it makes sense to lớn have sầu all that in one place and re-use it whenever you need lớn have a new object built in the same way. Fundamentally, that’s the use of the factory pattern.It’s a great idea to lớn have an interface for our factory và have our code reliant on it and not on a concrete factory

interface FamilyFactoryInterface public function create() : Family

Next, implement factory interface with the following class:

class FamilyFactory implements FamilyFactoryInterface  

public function create() : Family  

$family = new Family(); 

// initialize your family 

return $family;

Adapter Pattern

In Adapter Design Pattern, a class transforms the interface of one class to lớn another class.In this example we have a TextBook class that has a getTitle() và getAuthor() methods. The client expects a getTitleAndAuthor() method. To "adapt" SimpleBook for demoAdapter we have sầu an adapter class, BookAdapter, which takes in an instance of TextBook, và uses the TextBook getTitle() and getAuthor() methods in its own getTitleAndAuthor method.

Xem thêm: Sửa Lỗi Your Password Has Expired And Must Be Changed", Here'S The Fix (2020)

class TextBook 

private $title; private $author; function __construct($title_in, $author_in) $this->title = $title_in;

$this->author = $author_in;

function getTitle() return $this->title; function getAuthor() return $this->author; class BookAdapter  private $book; function __construct(TextBook $book_in) $this->book = $book_in; function getTitleAndAuthors() return $this->book->getTitle()." by ".$this->book->getAuthor(); // client writeln("BEGIN TESTING ADAPTER PATTERN"); writeln(""); $book = new TextBook("Gamma, Helm, Johnson, & Vlissides", "Design Patterns"); $bookAdapter = new BookAdapter($book); writeln("Author và Title: ".$bookAdapter->getTitleAndAuthor()); writeln(""); writeln("END TESTING ADAPTER PATTERN"); function writeln($line_in) echo $line_in.""; ?>

PHPhường. Singleton Pattern

In order lớn limit the instantiation of a class lớn a single object, a singleton pattern in PHP is used. This can be useful when only one object is needed across the system. It makes sense lớn allow access to only one instance of a certain class while designing website applications. In order khổng lồ prsự kiện the explicit creation of objects from the Singleton pattern class, a private constructor is utilized.

class Singleton public static function getInstance() static $instance = null; if (null === $instance) $instance = new static(); return $instance; protected function __construct() private function __clone() private function __wakeup() class SingletonChild extends Singleton$obj = Singleton::getInstance();var_dump($obj === Singleton::getInstance());$obj2 = SingletonChild::getInstance();var_dump($obj2 === Singleton::getInstance());var_dump($obj2 === SingletonChild::getInstance());?>

Observer Pattern in PHP

The PHP. Obhệ thống pattern is used to lớn alert the rest of the system about particular events in certain places.For instance, if we need to lớn create a Theater to show movies to the critics. We define the class Theater with the current method. Before presenting the movie, we want khổng lồ send messages khổng lồ the critics’ cell phones. Then, in the middle of the movie we want lớn stop the movie for 5 minutes lớn let the critics have an interval. Finally, after the end of the movie we want to lớn ask the critics to lớn leave their response. So, in the observer pattern for PHPhường, the obhệ thống object only gets notified when status is changed.

This is how code looks like -

class Theater  public function current(Movie $movie) : void  $critics = $movie->getCritics(); $this->message->send($critics, "..."); $movie->play(); $movie->pause(5); $this->progress->interval($critics) $movie->end(); $this->response->request($critics);

Decorator Pattern for PHP

The Decorator pattern is used when you want lớn alter the character of an object at run-time, & with that, reduce unnecessary inheritances và the number of classes. Well, it can be explained with examples. Let’s say we have sầu classes Sofa và Bed, & they both implement SleeperInterface.

interface SleeprInterface  public function sleep() : void;class Sofa implements SleeperInterface  public function sleep() : void // sleeps on sofa class Bed implements SleeperInterface  public function sleep() : void // sleeps on bed

Both the sofas & the beds have sầu the same behavior to lớn sleep. Now, we need other sofas & beds with additional functionality that will tell the users the sleep tracking when they sleep on the sofas or beds. With inheritance we can solve sầu this problem just lượt thích this:

class SmartSofa extends Sofa  public function sleep() : void parent::sleep(); $this->sleepHours(); class SmartBed extends Window  public function sleep() : void parent::sleep(); $this->sleepHours();

Now we have 4 classes in total. However, we could solve this problem with 3 classes only with the Decorator pattern. Here’s how:

class SmartSleeper implements SleeperInterface private $sleeper; public function __construct(SleeperInterface $sleeper) $this->sleeper = $sleeper; public function sleep() : void  $this->sleeper->sleep(); $this->sleepHours(); $sofa = new Sofa();$bed = new Bed();$smartSofa = new SmartSleeper($sofa);$smartBed = new SmartSleeper($bed);

Here, we have introduced a new type of a sleeper that acts lượt thích a proxy but with an extra functionality on top of it.

Leveraging Design Patterns in Drupal 8

While there are many design patterns already established within Drupal before Drupal 8, Drupal 8 now consists of a lot of patterns that were previously unavailable. Some of these new patterns completely replace some older ones, while others introduce some new features khổng lồ Drupal 8.

The kiến thiết patterns used in Drupal 8 includes:

Object-Oriented Programming Pattern (OOP)Dependency InjectionsFactory PatternSingleton Pattern

OOPhường. is not really a single pattern, but a completely radical way of conceptualizing & structuring codes that goes way beyond just thiết kế patterns. It is the basis for a lot of popular software design patterns in use today, including those used in Drupal 8. It was introduced in Drupal 7, but it was not used extensively, và it was not required. The situation in Drupal 8 is now different, it is used widely, và it is required.

Dependency Injection

Dependency Injection is that software kiến thiết pattern that would allow you to remove sầu hard-coded dependencies and also make it possible lớn change them either on runtime or at compile time. Adding dependency injection is easy and it does not meddle with your existing code. Drupal 8 introduced the concept of services in order to lớn decouple the reusable functionalities. core.services.yml is an example for dependency injection in Drupal 8. We have sầu already discussed about Factory Pattern & Singleton Pattern in PHPhường above