数据对象映射模式

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

下面实现一个ORM类,将复杂的sql语句映射成对象属性的操作

User.php

<?php
/*
*
*/
class User
{
    public $id;
    public $name;
    public $mobile;
    public $regtime;
    
    function __construct($id)
    {
        $this->db = new \Database\MYSSQLi();
        $this->db->connect('localhost', 'root', 'root', 'test');
        $res = $this->db->query("select * from test");
        $data = $res->fetch_assoc();
        
        $this->id = $data['id'];
        $this->name = $data['name'];
        $this->mobile = $data['mobile'];
        $this->regtime = $data['regtime'];
    }
    
    function __destruct()
    {
        $this->db->query("update test set name='{$this->name}',...");
    }
}

使用

<?php

$user = new ..\User(1);

$user->mobile = '12321312';
$user->name = 'test';
$user->regitime = time();

下面将结合使用前面博客讲到的工厂模式和注册模式实现ORM类

Factory.php

<?php
/*
*工厂模式
*/
class Factory
{
    ...
        
    static function createDatabase()
    {
        $db = Database::getInstance();
        Register::set('db1', $db);
        return $db;
    }
    
    static function getUser($id)
    {
        //采用注册器模式,结合前面有关注册器模式的博客
        $key = 'user_'.$id;
        $user = Register::get($key);
        if(!$user) {
            $user = new User($id);
            Register::set($key, $user);
        }
        return $user;
    }
}

index.php

<?php
/*
*
*/
class Page
{
    function index()
    {
        $user = new ..\Factory::getUser(1);
        $user->name = 'test';
        
        $this->test();
    }
    
    function test()
    {
        $user = new ..\Factory::getUser(1);
        $user->mobile = '12321312';
    }
}

本文由 一切随风 创作,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论