2012-10-26 2 views
1

젠드 프레임 워크를 기반으로 애플리케이션을 시작합니다. 이 응용 프로그램은 데이터베이스 이외의 여러 데이터 소스를 사용할 수 있어야합니다. 예를 들어 웹 서비스.젠드 프레임 워크로 여러 데이터 소스 활용하기

이 시나리오를 허용하기 위해 내 모델을 구조화하는 방법을 읽었습니다. 나는 이것 (DataMapper Pattern, Service Pattern, Adaptor Layer, etc.)에 대한 해결책을 제공하는 것처럼 보일 수있는 다양한 개념들을 보았다. 그러나, 나는이 모든 것을 재사용 및 확장 가능한 코드베이스에 통합하는 방법에 대해 여전히 혼란 스럽다.

전 zend 프레임 워크에서 작업했으며 이전에는 mysql 테이블과 함께 작동합니다. 예를 들어 사용자 테이블이있는 경우 ... 간단히 말해서 사용자 도메인의 비즈니스 로직을 포함하는 내 모델의 사용자 클래스와 사용자 테이블의 행을 나타내는 Zend_Db_Table_Row_Abstract를 확장하는 사용자 클래스가 있습니다.

필자는 내 모델과 코드베이스를 구성하여 필자가 $ users-> fetchAll()을 호출하고 내 데이터 소스에 관계없이 사용자 개체 컬렉션을 얻을 수 있도록 최선의 방법을 결정할 수 있습니까?

답변

4

기본적으로 이전과 동일하게 작동합니다. 단지 Zend_Db_Table_Gateway 대신 My_UserGateway_Whatever을 사용합니다. 먼저 인터페이스를 만들 :

interface UserGateway 
{ 
    /** 
    * @return array 
    * @throws UserGatewayException 
    */ 
    public function findAll(); 
} 

을 우리는 소비 코드에 표시 콘크리트 게이트웨이에서 예외 싶지 않는, 그래서 우리는 모든 캐치로 UserGatewayException를 추가 : 다음

class UserGatewayException extends RuntimeException 
{} 

것을 구현하는 클래스를 추가 인터페이스 :

마찬가지로 데이터베이스 소스를 사용하려는 경우 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를 만들 때 쉽게 하나를 주입 또는 생성자에 다른 게이트웨이와 코드를 사용한 관계없이의 게이트웨이를 작동 할 수 있습니다 WebService에 대한,

$foo = SomethingUsingUsers(
    new My_UserGateway_Database(
     new Zend_Db_Table('User') 
    ) 
) 

또는 :

$foo = SomethingUsingUsers(
    new My_UserGateway_Webservice(
     // any additional dependencies 
    ) 
) 
관련 문제