## 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();
~~~
- 序言
- 第1章 課程簡介
- 1-1 大話PHP設計模式課程簡介
- 第2章 開發環境準備
- 2-1 關于PHPStorm使用
- 2-2 關于編程字體選擇
- 2-3 關于運行環境搭建
- 第3章 命名空間與Autoload
- 3-1 關于命名空間
- 3-2 類自動載入
- 3-3 開發一個PSR-0的基礎框架
- 第4章 PHP面向對象
- 4-1 SPL標準庫簡介
- 4-2 PHP鏈式操作的實現
- 4-3 PHP魔術方法的使用
- 第5章 三種基礎設計模式
- 5-1 工廠模式
- 5-2 單例模式
- 5-3 注冊樹模式
- 第6章 適配器模式
- 6-1 適配器模式
- 第7章 策略模式
- 7-1 策略模式的實現和使用
- 7-2 策略模式的控制反轉
- 第8章 數據對象映射模式
- 8-1 數據對象映射模式之簡單案例實現
- 8-2 數據對象映射模式之復雜案例實現
- 第9章 觀察者模式
- 第10章 原型模式
- 第11章 裝飾器模式
- 第12章 迭代器模式
- 第13章 代理模式
- 第14章 綜合實戰
- 14-1 面向對象設計基本原則
- 14-2 MVC結構
- 14-3 自動加載配置
- 14-4 從配置中生成數據庫連接
- 14-5 裝飾器模式在MVC中的使用
- 14-6 觀察者模式在MVC程序中的使用
- 14-7 代理模式在MVC程序中的使用
- 14-8 課程小結