PHP. Design patterns have sầu proven to be extremely useful lớn developers và is a major problem solver. To write efficient code, developers must follow best practices. PHPhường Design patterns is an Object-oriented programming (OOP) concept that is now also used in Drupal 8 projects. With Drupal 8 adopting modern PHP. and OOPhường. concepts, kiến thiết patterns can be leveraged for a cleaner and more robust programming.
Bạn đang xem: Design patterns in php
What are Design Patterns in PHP?
In software engineering, a Design Pattern is a general repeatable solution to lớn commonly occurring problem in software Design. Good Object-oriented designs should be reusable, maintainable and extensible and Design Patterns in PHPhường could be very helpful in doing that. It does not only help in solving problems, it implies an optimal way addressing comtháng challenges.
Benefits of using PHPhường Design Patterns
Major benefits of thiết kế patterns in PHPhường are :PHP Design patters help in solving repetitive sầu problems faced during developmentOther developers looking at your code won’t have sầu to struggle to lớn understvà as the code is well structured with design patternsFollowing best practices helps build more robust softwareIt helps make development faster and 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, to create objects that can be decoupled from the system that implemented them.
Structural Patterns: This eases the design by identifying simple ways lớn realize relationships between entities
Behavioral Patterns: They are used to lớn manage relationships, responsibilities, & algorithms between objects
A factory pattern is used khổng lồ build an object. That’s right — build an object and not create an object. When we build the object, we first create it and then initialize it. Usually, it requires khổng lồ apply certain lô ghích và perform multiple steps. With that, it makes sense lớn have sầu all that in one place và re-use it whenever you need to 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 have sầu an interface for our factory and have sầu 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
In Adapter Design Pattern, a class transforms the interface of one class 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, and uses the TextBook getTitle() & getAuthor() methods in its own getTitleAndAuthor method.
Xem thêm: " Kv Là Gì ? Tìm Hiểu Kva, Kv, Kw Là Gì
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, và Vlissides", "Design Patterns"); $bookAdapter = new BookAdapter($book); writeln("Author and Title: ".$bookAdapter->getTitleAndAuthor()); writeln(""); writeln("END TESTING ADAPTER PATTERN"); function writeln($line_in) echo $line_in.""; ?>
PHPhường Singleton Pattern
In order khổng lồ 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 to allow access to only one instance of a certain class while designing web applications. In order lớn 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 PHPhường 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 khổng lồ create a Theater khổng lồ show movies to lớn the critics. We define the class Theater with the current method. Before presenting the movie, we want to lớn sover messages lớn the critics’ cell phones. Then, in the middle of the movie we want to lớn stop the movie for 5 minutes lớn let the critics have sầu an interval. Finally, after the end of the movie we want lớn ask the critics to lớn leave their response. So, in the obVPS pattern for PHP., 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 to 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 classes Sofa & Bed, và 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 và the beds have sầu the same behavior to lớn sleep. Now, we need other sofas và 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 this problem just like 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 sầu 4 classes in total. However, we could solve sầu 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 thiết kế 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 lớn Drupal 8.
Xem thêm: Sports Car Racing For Android, Download Racing Game Apk Android App Online
The kiến thiết patterns used in Drupal 8 includes:Object-Oriented Programming Pattern (OOP)Dependency InjectionsFactory PatternSingleton Pattern
OOP is not really a single pattern, but a completely radical way of conceptualizing & structuring codes that goes way beyond just kiến thiết 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, and it was not required. The situation in Drupal 8 is now different, it is used widely, and it is required.
Dependency Injection is that software kiến thiết pattern that would allow you lớn remove sầu hard-coded dependencies và also make it possible to 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 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 and Singleton Pattern in PHPhường above