在PHP开发领域,面向对象设计模式(OOP Design Patterns)是构建可重用、可维护和可扩展代码的关键。本文将深入探讨PHP中的几种常见设计模式,并对比不同框架对这些模式的实现和应用。
1. 设计模式概述
设计模式是一套被反复使用、多数人知晓、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性。
PHP中的设计模式主要包括:
- 单例模式(Singleton)
- 工厂模式(Factory)
- 适配器模式(Adapter)
- 观察者模式(Observer)
- 装饰者模式(Decorator)
- 策略模式(Strategy)
- 模板方法模式(Template Method)
2. 单例模式
单例模式确保一个类只有一个实例,并提供一个访问它的全局访问点。
Laravel实现
class Singleton
{
private static $instance;
public static function getInstance()
{
if (self::$instance == null) {
self::$instance = new Singleton();
}
return self::$instance;
}
}
YII实现
class Singleton
{
private static $instance;
public static function getInstance()
{
if (self::$instance == null) {
self::$instance = new Singleton();
}
return self::$instance;
}
}
3. 工厂模式
工厂模式定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
Laravel实现
interface LoggerFactory
{
public function make($name);
}
class MonologLoggerFactory implements LoggerFactory
{
public function make($name)
{
return new \Monolog\Logger($name);
}
}
YII实现
interface LoggerFactory
{
public function make($name);
}
class MonologLoggerFactory implements LoggerFactory
{
public function make($name)
{
return new \Monolog\Logger($name);
}
}
4. 适配器模式
适配器模式允许将一个类的接口转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以一起工作。
Laravel实现
interface PaymentGateway
{
public function pay();
}
class StripePaymentGateway implements PaymentGateway
{
public function pay()
{
return 'Payment processed by Stripe';
}
}
class PayPalPaymentGateway implements PaymentGateway
{
public function pay()
{
return 'Payment processed by PayPal';
}
}
class PaymentAdapter
{
private $gateway;
public function __construct(PaymentGateway $gateway)
{
$this->gateway = $gateway;
}
public function pay()
{
return $this->gateway->pay();
}
}
YII实现
interface PaymentGateway
{
public function pay();
}
class StripePaymentGateway implements PaymentGateway
{
public function pay()
{
return 'Payment processed by Stripe';
}
}
class PayPalPaymentGateway implements PaymentGateway
{
public function pay()
{
return 'Payment processed by PayPal';
}
}
class PaymentAdapter
{
private $gateway;
public function __construct(PaymentGateway $gateway)
{
$this->gateway = $gateway;
}
public function pay()
{
return $this->gateway->pay();
}
}
5. 观察者模式
观察者模式定义对象间的一对多依赖关系,当一个对象改变状态,所有依赖于它的对象都会得到通知并自动更新。
Laravel实现
interface Observer
{
public function update($event);
}
interface Subject
{
public function attach(Observer $observer);
public function detach(Observer $observer);
public function notify();
}
class User implements Subject
{
private $observers = [];
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function attach(Observer $observer)
{
$this->observers[] = $observer;
}
public function detach(Observer $observer)
{
$key = array_search($observer, $this->observers, true);
if ($key !== false) {
unset($this->observers[$key]);
}
}
public function notify()
{
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
public function setName($name)
{
$this->name = $name;
$this->notify();
}
}
class UserObserver implements Observer
{
public function update($user)
{
echo "User {$user->name} has been updated.\n";
}
}
YII实现
interface Observer
{
public function update($event);
}
interface Subject
{
public function attach(Observer $observer);
public function detach(Observer $observer);
public function notify();
}
class User implements Subject
{
private $observers = [];
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function attach(Observer $observer)
{
$this->observers[] = $observer;
}
public function detach(Observer $observer)
{
$key = array_search($observer, $this->observers, true);
if ($key !== false) {
unset($this->observers[$key]);
}
}
public function notify()
{
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
public function setName($name)
{
$this->name = $name;
$this->notify();
}
}
class UserObserver implements Observer
{
public function update($user)
{
echo "User {$user->name} has been updated.\n";
}
}
6. 装饰者模式
装饰者模式动态地给一个对象添加一些额外的职责,就增加功能来说,装饰者模式比生成子类更为灵活。
Laravel实现
interface Component
{
public function doSomething();
}
class ConcreteComponent implements Component
{
public function doSomething()
{
return "ConcreteComponent doing something";
}
}
class Decorator implements Component
{
protected $component;
public function __construct(Component $component)
{
$this->component = $component;
}
public function doSomething()
{
return $this->component->doSomething() . " with decorator";
}
}
YII实现
interface Component
{
public function doSomething();
}
class ConcreteComponent implements Component
{
public function doSomething()
{
return "ConcreteComponent doing something";
}
}
class Decorator implements Component
{
protected $component;
public function __construct(Component $component)
{
$this->component = $component;
}
public function doSomething()
{
return $this->component->doSomething() . " with decorator";
}
}
7. 策略模式
策略模式定义一系列算法,把它们一个个封装起来,并使它们可以相互替换。策略模式让算法的变化独立于使用算法的客户。
Laravel实现
interface Strategy
{
public function execute();
}
class ConcreteStrategyA implements Strategy
{
public function execute()
{
return "Strategy A executed";
}
}
class ConcreteStrategyB implements Strategy
{
public function execute()
{
return "Strategy B executed";
}
}
class Context
{
private $strategy;
public function __construct(Strategy $strategy)
{
$this->strategy = $strategy;
}
public function setStrategy(Strategy $strategy)
{
$this->strategy = $strategy;
}
public function execute()
{
return $this->strategy->execute();
}
}
YII实现
interface Strategy
{
public function execute();
}
class ConcreteStrategyA implements Strategy
{
public function execute()
{
return "Strategy A executed";
}
}
class ConcreteStrategyB implements Strategy
{
public function execute()
{
return "Strategy B executed";
}
}
class Context
{
private $strategy;
public function __construct(Strategy $strategy)
{
$this->strategy = $strategy;
}
public function setStrategy(Strategy $strategy)
{
$this->strategy = $strategy;
}
public function execute()
{
return $this->strategy->execute();
}
}
8. 模板方法模式
模板方法模式定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法让子类在不改变算法结构的情况下,重新定义算法中的某些步骤。
Laravel实现
abstract class Template
{
protected function stepA()
{
echo "Step A\n";
}
protected function stepB()
{
echo "Step B\n";
}
public function execute()
{
$this->stepA();
$this->stepB();
}
}
class ConcreteTemplate extends Template
{
protected function stepB()
{
echo "ConcreteTemplate Step B\n";
}
}
YII实现
abstract class Template
{
protected function stepA()
{
echo "Step A\n";
}
protected function stepB()
{
echo "Step B\n";
}
public function execute()
{
$this->stepA();
$this->stepB();
}
}
class ConcreteTemplate extends Template
{
protected function stepB()
{
echo "ConcreteTemplate Step B\n";
}
}
9. 总结
本文深入解析了PHP中几种常见的设计模式,并通过Laravel和YII两个框架的实现进行对比。这些设计模式在PHP开发中具有重要的应用价值,可以帮助开发者写出更加优雅、可维护和可扩展的代码。在实际开发中,我们可以根据项目需求和场景选择合适的设计模式,以提高代码质量和开发效率。
