它基本上和以前一樣,只是代替Zend_Db_Table_Gateway
而使用My_UserGateway_Whatever
,例如,首先創建一個接口:
interface UserGateway
{
/**
* @return array
* @throws UserGatewayException
*/
public function findAll();
}
我們不想從具體網關例外出現在消費代碼,所以我們增加了UserGatewayException作爲包羅萬象:
class UserGatewayException extends RuntimeException
{}
然後加入實現一個類接口:
class My_UserGateway_Webservice implements UserGateway
{
public function findAll()
{
try {
// insert logic to fetch from the webservice
return $userData;
} catch (Exception $e) {
throw new UserGatewayException($e->getMessage(), $e->getCode, $e);
}
}
// … more code
}
同樣,如果你想使用一個數據庫源,你可以寫爲Zend_Db_ *類,如適配器
class My_UserGateway_Database implements UserGateway
{
private $tableDataGateway;
public function __construct(Zend_Db_Table_Abstract $tableDataGateway)
{
$this->tableDataGateway = $tableDataGateway;
}
public function findAll()
{
try {
return $this->tableDataGateway->select()->blah();
} catch (Exception $e) {
throw new UserGatewayException($e->getMessage(), $e->getCode, $e);
}
}
// … more code
}
如果您需要另一個數據提供者,確保他們實現這個接口,所以你可以依靠findAll
方法在那裏。讓您的消費類別取決於界面,例如
class SomethingUsingUsers
{
private $userGateway;
public function __construct(UserGateway $userGateway)
{
$this->userGateway = $userGateway;
}
public function something()
{
try {
$users = $this->userGateway->findAll();
// do something with array of user data from gateway
} catch (UserGatewayException $e) {
// handle Exception
}
}
// … more code
}
現在,當您創建SomethingUsingUsers
您可以輕鬆地將一個或另一個網關到構造和無論哪個你的代碼將工作網關你使用:
$foo = SomethingUsingUsers(
new My_UserGateway_Database(
new Zend_Db_Table('User')
)
)
,或者爲WebService:
$foo = SomethingUsingUsers(
new My_UserGateway_Webservice(
// any additional dependencies
)
)