1

我有我的業務對象的存儲庫,我需要根據數據創建不同的對象。我應該直接在repo中創建它們還是將其移動到其他地方 - 工廠或業務邏輯層中的某個類?我應該在哪裏創建對象?庫?廠?

/** 
* @returns Applier 
*/ 
class ApplierRepository implements IApplierRepositoryInterface { 
    //some code 
    public function find($id) { 
    $data = $this->findBySql($id); 

    //Is it a business logic? 
    if($data['profile_id'] != null) 
     $object = new ProfileApplier(); 
    if($data['user_id'] != null) { 
     $user = $this->userRepository->find($data['user_id']); 
     $object = new UserApplier($user); 
    } 
    //... 
    return $object; 
    } 
} 

回答

1

我會考慮作爲抽象層次數據之間的訪問級別和你應用程序邏輯。 你有什麼在你的找到()方法實際上是一個工廠方法

爲了把事情說清楚,想象一下,你需要測試ramework來測試你的類的邏輯。你會怎麼做?好像你ProfileApplierUserApplier等施放調用一些數據源以檢索用戶數據。

在測試方法中,您需要用測試方法替換那些數據源。您還需要替換數據源訪問方法。這就是設計用於模式的模式。

更清潔的方法是類似以下內容:

class AppliersFactory { 
    IApplierRepository applierRepository; 

    public AppliersFactory(IApplierRepository repo) 
    { 
    $this->applierRepository = repo; 
    } 

    // factory method, it will create your buisness objects, regardless of the data source 
    public function create($data) { 
    if($data['profile_id'] != null) 
     $return new ProfileApplier(); 
    if($data['user_id'] != null) { 
     $user = $this->applierRepository->find($data['user_id']); 
     $object = new UserApplier($user); 
    } 
    //... 
    return $object; 
    } 
} 

使用這個倉庫在實際應用

class RealApplierDataStorageRepository implements IApplierRepositoryInterface { 
    //some code, retrieves data from real data sources 
    public function find($id) { 
    //... 
    } 
} 

,並使用這一個在測試模塊,以測試你的邏輯

class TestApplierDataStorageRepository implements IApplierRepositoryInterface { 
    // some code, retrieves data from test data sources (lets say, some arrays of data) 
    public function find($id) { 
    //... 
    } 
} 

希望它有幫助

+0

非常感謝!這就是我一直在尋找的。 –

+0

不客氣! –

相關問題