【发布时间】:2015-10-17 21:13:59
【问题描述】:
我的项目中有实体和存储库。为了简化,我有
EntityInterfaceUserEntityBusinessEntity
界面:
interface Entity
{
/**
* @return EntityId
*/
public function getId();
}
实现
class UserEntity implements Entity
{
/**
* @return EntityId
*/
public function getId(){
//...do something here for return
return $userId;
}
}
和
class BusinessEntity implements Entity
{
/**
* @return EntityId
*/
public function getId(){
//...do something here for return
return $userId;
}
}
我想定义一个 Repository 基础功能,比如save,所以我的界面看起来像:
interface Repository
{
/**
* @param Entity $entity
*
* @throws \InvalidArgumentException If argument is not match for the repository.
* @throws UnableToSaveException If repository can't save the Entity.
*
* @return Entity The saved entity
*/
public function save(Entity $entity);
}
后来,我为不同类型的存储库提供了不同的接口,例如UserRepository 和BusinessRepository
interface BusinessRepository extends Repository
{
/**
* @param BusinessEntity $entity
*
* @throws \InvalidArgumentException If argument is not match for the repository.
* @throws UnableToSaveException If repository can't save the Entity.
*
* @return Entity The saved entity
*/
public function save(BusinessEntity $entity);
}
上面的代码失败了,因为Declaration must be compatible with Repository...
然而 BusinessEntity 实现了 Entity,所以它是兼容的。
我有许多类型的实体,所以如果我不能输入提示,我总是需要检查传递的实例是否是我需要的实例。这很愚蠢。
以下代码再次失败:
class BusinessRepository implements Repository
{
public function save(BusinessEntity $entity)
{
//this will fail, however BusinessEntity is an Entity
}
}
【问题讨论】: