The "Example 2" data Object mapping mode combines the use of "Factory mode" and "Registration mode".
Entry file index.php:
<?PHPDefine(' BASEDIR ', __dir__);//defining a root directory constantincludeBASEDIR. ' /common/loader.php '; Spl_autoload_register (' \\common\\loader::autoload ');Echo' <meta http-equiv= ' Content-type "content=" Text/html;charset=utf8 ">";classpage{functionindex () {//use the factory method to generate the object instead of the direct new $user= Common\factory::getuser (1); $user->name = ' Ozil '; $this-test (); Echo' Success '; } functionTest () {//The operation of the object's properties completes the operation of the database. $user= Common\factory::getuser (1); $user->mobile = ' 13912345678 '; $user->regtime =Date("Y-m-d h:i:s", Time()); }}$page=NewPage ();$page->index ();
The $user object in index () and test () is the same object.
Factory mode File common\factory.php
<?phpnamespace Common;classfactory{Static functionCreateDatabase () {$db= Database::getinstance (); //after the database object is obtained, map the object to the global treeRegister::set (' db1 ',$db);//DB1 is the alias of the map return $db; } Static functionGetUser ($id){ //Registrar mode $key= ' User_ '.$id; $user= Register::get ($key); if(!$user){ $user=NewUser ($id); Register:: Set ($key,$user); } return $user; }}
Access to the portal file allows you to modify the data in the Test Database user table with ID 1.
PHP design Pattern Notes and summaries (10) Data Object Mapping mode 2