PHP设计模式之数据对象映射模式

数据对象映射模式

将对象和数据存储映射起来,对一个对象的操作会映射为对数据存储的操作。

下面例子结合数据对象映射模式、工厂模式、注册树模式,将复杂的SQL语句映射成对象属性的操作。

User.php(用户类)

<?php
namespace core;

class User
{
    public $id;
    public $name;
    public $tel;

    protected $db;

    public function __construct($id)
    {
        $this->db = new \PDO("mysql:host=127.0.0.1;port=3306;dbname=test;charset=utf8", 'root', 'lxl');
        $stat = $this->db->query("SELECT * FROM USER WHERE id = {$id}");
        $res = $stat->fetch(\PDO::FETCH_ASSOC);
        $this->id = $res['id'];
        $this->name = $res['name'];
        $this->tel = $res['tel'];
    }

    public function save()
    {
        $this->db->exec("UPDATE USER SET name = '{$this->name}', tel = {$this->tel} WHERE id = {$this->id}");
    }

    public function __destruct()
    {
        $this->save();
    }
}

Factory.php(工厂类)

<?php
namespace core;

class Factory
{
    static function createUser($id)
    {
        $key = "user_" . $id;
        // 判断注册树中是否存在该实例
        $user = RegisterTree::get($key);
        if (!$user) {
            $user = new User($id);
            RegisterTree::set($key, $user);
        }
        return $user;
    }
}

RegisterTree.php(注册树类)

<?php
namespace core;

class RegisterTree
{
    protected static $objects;  // 存放注册对象
    // 注册
    public static function set($alias, $object)
    {
        self::$objects[$alias] = $object;
    }
    // 取实例化对象
    public static function get($alias)
    {
        return self::$objects[$alias];
    }
    // 取消注册
    public static function _unset($alias)
    {
        unset(self::$objects[$alias]);
    }
}

index.php

class Test
{
    public function editAll()
    {
        $user = \core\Factory::createUser(1);
        $user->name = "user1234567";
        $this->editTel();
        $user->save();
    }

    public function editTel()
    {
        $user = \core\Factory::createUser(1);
        $user->tel = 1591888888;
    }
}

$test = new Test();
$test->editAll();

猜你喜欢

转载自blog.csdn.net/qq_36045946/article/details/81009104
今日推荐