1. Factory pattern: Separate object creation and business logic, and create objects of specified types through factory classes. 2. Observer pattern: Allows subject objects to notify observer objects of their state changes, achieving loose coupling and observer pattern.
PHP design pattern practical case analysis
Foreword
Design pattern is the solution Examples of proven solutions to common software design problems. They help create reusable, maintainable, and extensible code. In this article, we’ll explore some of the most commonly used design patterns in PHP and provide practical examples.
Factory Pattern
The best way to create objects is to separate the instantiation process from the business logic. The factory pattern uses a central factory class to decide which type of object to create.
Practical case: Creating a shape factory
interface Shape { public function draw(); } class Square implements Shape { public function draw() { echo "Drawing a square.\n"; } } class Circle implements Shape { public function draw() { echo "Drawing a circle.\n"; } } class ShapeFactory { public static function createShape(string $type): Shape { switch ($type) { case "square": return new Square(); case "circle": return new Circle(); default: throw new Exception("Invalid shape type."); } } } // Usage $factory = new ShapeFactory(); $square = $factory->createShape("square"); $square->draw(); // 输出:Drawing a square.
Observer pattern
The observer pattern allows an object (theme) Notify other objects (observers) about changes in their state.
Practical Case: Creating a Blog System
interface Observer { public function update(Subject $subject); } class Subject { protected $observers = []; public function attach(Observer $observer) { $this->observers[] = $observer; } public function detach(Observer $observer) { $key = array_search($observer, $this->observers); if ($key !== false) { unset($this->observers[$key]); } } public function notify() { foreach ($this->observers as $observer) { $observer->update($this); } } } class Post extends Subject { private $title; private $body; // ... Post related methods public function publish() { $this->notify(); } } class EmailObserver implements Observer { public function update(Subject $subject) { // Send an email notification for the new post. } } class PushObserver implements Observer { public function update(Subject $subject) { // Send a push notification for the new post. } } // Usage $post = new Post(); $observer1 = new EmailObserver(); $observer2 = new PushObserver(); $post->attach($observer1); $post->attach($observer2); $post->publish(); // Sends email and push notifications for the new post.
Summary
We explored factory and observer design through practical examples Patterns, explains how design patterns can improve code reusability, maintainability, and scalability.
The above is the detailed content of PHP design pattern practical case analysis. For more information, please follow other related articles on the PHP Chinese website!