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



// 数据对象映射模式
class User
{
    public $id;
    public $name;
    public $mobile;
    public $regtime;

    private $dataFile;


    public function __construct($id)
    {
        $this->dataFile = "user.$id.data";
        if(file_exists($this->dataFile)) {
            $data = json_decode(file_get_contents($this->dataFile), 1);

            $this->name = $data['name'];
            $this->mobile = $data['mobile'];
            $this->regtime = $data['regtime'];
        }
    }

    public function __destruct()
    {
        return file_put_contents($this->dataFile, json_encode([
            'name' => $this->name,
            'mobile' => $this->mobile,
            'regtime' => $this->regtime
        ]));
    }
}

// 结合注册器模式
class Register
{
    private static $object;

    public static function get($key)
    {
        return isset(self::$object[$key]) ? self::$object[$key] : false;
    }

    public static function set($key, $obj)
    {
        self::$object[$key] = $obj;
    }
}


// 结合工厂模式
class Factory
{
    public static function getUser($id)
    {
        if(!$user = Register::get($id)) {
            $user = new User($id);
            Register::set($id, $user);
            echo "register set \n";
        }
        return $user;
    }
}


class Page
{
    public function index()
    {
        $user = Factory::getUser(1);
        $user->mobile = '15165854585';
        $user->name = 'test';
        $user->regtime = time();
    }

    public function test()
    {
        $user = Factory::getUser(1);
        $user->mobile = '15165854585';
        $user->name = 'test23333';
        $user->regtime = time();
    }
}



$page = new Page;
$page->index();
$page->test();



你可能感兴趣的:(PHP,PHP)