«

PHP 常用设计模式

时间:2026-10-8 07:24     作者:emer     分类: 无


PHP 常用设计模式

设计模式是写好代码的经验总结,常用的几种要掌握。

1. 单例模式

整个项目只有一个实例,比如数据库连接。

class Db
{
    private static $instance = null;

    private function __construct() {}

    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

$db = Db::getInstance();

2. 工厂模式

根据参数创建不同的对象。

class Factory
{
    public static function make($type)
    {
        $class = ucfirst($type);
        return new $class();
    }
}

$user = Factory::make('user');
$order = Factory::make('order');

3. 观察者模式

一个对象状态变化,通知所有观察者。

interface Observer
{
    public function update($event);
}

class Event
{
    private $observers = [];

    public function add(Observer $observer)
    {
        $this->observers[] = $observer;
    }

    public function trigger($event)
    {
        foreach ($this->observers as $ob) {
            $ob->update($event);
        }
    }
}

4. 常用场景

5. 设计原则

总结

PHP 常用设计模式要点:

设计模式是工具,解决问题才是目的。

标签: PHP 设计模式 单例 开发 工厂