PHP設計モードノートとまとめ(10)データオブジェクトマッピングモード2


【例2】データオブジェクトマッピングモードは、【ファクトリモード】と【登録モード】を組み合わせたものである.
入口ファイルphp:
<?php
define('BASEDIR',__DIR__); //       
include BASEDIR.'/Common/Loader.php';
spl_autoload_register('\\Common\\Loader::autoload');
echo '<meta http-equiv="content-type" content="text/html;charset=utf8">';

class Page{
    function index(){
        //          ,     new
        $user = Common\Factory::getUser(1);
        $user->name = 'Ozil';
        
        $this->test();
        echo 'success';
    }
    
    function test(){
        //                   
        $user = Common\Factory::getUser(1);
        $user->mobile = '13912345678';
        $user->regtime = date("Y-m-d H:i:s",time()); 
    }
}

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

index()とtest()の$userオブジェクトは同じオブジェクトです. 
 
工場モードファイルphp
<?php
namespace Common;

class Factory{
    static function createDatabase(){
        $db = Database::getInstance();
        //
        Register::set('db1',$db);//db1      
        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;
    }
}

 
エントリファイルにアクセスするとtestデータベースuserテーブルのidが1のデータを変更できます.