ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## 8-2 数据对象映射模式之案例复杂实现 ### 1. 现在的不足实例 *D:\wamp\www\demo\oop\framework\index.php* ~~~ <?php ...... class Page { function index() { // 实例化1个用户表对象:User $user = new Think\User(3); $this->test(); $user->name = '修改后的名字'; } function test() { $user = new Think\User(3); $user->passwd = md5('111'); } } $page = new Page(); $page->index(); ~~~ 不足的地方是:创建了2个对象。我们使用工厂模式、注册模式来完善数据对象映射。 ## 使用工厂方法而不是直接new 好处:类的名称发送改变,只需要修改工厂类中的类名即可。 *D:\wamp\www\demo\oop\framework\Think\Factory.php* ~~~ static function getUser($id) { $user = new User($id); return $user; } ~~~ *D:\wamp\www\demo\oop\framework\index.php* ~~~ class Page { function index() { // 实例化1个用户表对象:User $user = Think\Factory::getUser(4); $user->name = 'zhangsan'; $this->test(); } function test() { $user2 = Think\Factory::getUser(4); $user2->passwd = 333; } } $page = new Page(); $page->index(); $page->test(); ~~~ ### 使用注册模式获取User对象 *D:\wamp\www\demo\oop\framework\Think\Factory.php* ~~~ // 使用注册模式 static function getUser($id) { $key = 'user_'.$id; $user = Register::get($key); if (!$user) { $user = new User($id); Register::set($key, $user); } return $user; } ~~~ *D:\wamp\www\demo\oop\framework\index.php* ~~~ <?php // 入口文件 define('BASEDIR', __DIR__); include BASEDIR . '/Think/Loder.php'; spl_autoload_register('\\Think\\Loder::autoload'); header("Content-Type:text/html charset=utf-8"); echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"; class Page { function index() { // 实例化1个用户表对象:User $user = Think\Factory::getUser(4); $user->name = 'zhangsan999'; var_dump($user); echo "ok"; } function test() { $user = Think\Factory::getUser(4); $user->passwd = 333999; var_dump($user); } } $page = new Page(); $page->index(); $page->test(); ~~~