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

不客气! –

相关问题