■実装
とりあえずパターンの要ではないクラス。
class Item { private $_id; private $_name; public function __construct($id, $name) { $this->_id = $id; $this->_name = $name; } public function getId() { return $this->_id; } public function getName() { return $this->_name; } }
ItemDao.php
interface ItemDao { public function findById($id); }
DbItemDao.php
DBからアイテムデータを取得して生成したインスタンスを返す本番用クラス。
class DbItemDao implements ItemDao { public function findById($id) { $fh = fopen('data.txt', 'r'); $item = null; while($buffer = fgets($fh, 4096)){ $id1 = trim(substr($buffer, 0, 10)); $name = trim(substr($buffer, 10)); if($id === (int) $id1){ $item = new Item($id1, $name); break; } } fclose($fh); return $item; } }
MockItemDao.php
ダミーデータで作ったインスタンスを返すテスト用クラス。
class MockItemDao implements ItemDao { public function findById($id) { $item = new Item($id, 'dummy'); return $item; } }
ItemDaoProxy.php
class ItemDaoProxy { private $_dao; private $_cache; public function __construct(ItemDao $dao) { $this->_dao = $dao; $this->_cache = array(); } public function findById($id) { if(array_key_exists($id, $this->_cache)){ return $this->_cache[$id]; } $this->_cache[$id] = $this->dao->findById($id); return $this->_cache[$id]; } }
■クライアントコード
以下のようにすることで使うことができる。
switch($mode){ case 'test': $dao = new MockItemDao(); break; case 'production': $dao = new DbItemDao(); break; } $proxy = new ItemDaoProxy($dao);