开门见山。
abstract class AbstractRepository {
private $mapper;
public function __construct(AbstractMapper $mapper) {
$this->mapper = $mapper;
}
public function save(AbstractEntity $entity) {
return $this->mapper->save($entity);
}
public function delete(AbstractEntity $entity) {
return $this->mapper->delete($entity);
}
}
class UserRepository extends AbstractRepository {
private $userMapper;
public function __construct(UserMapper $userMapper) {
parent::__construct($userMapper);
$this->userMapper = $userMapper;
}
public function fetchByUsername($username) {
return $this->userMapper->fetch( array('username' => $username) );
}
VS
abstract class AbstractRepository {
// Different visibility
protected $mapper;
public function __construct(AbstractMapper $mapper) {
$this->mapper = $mapper;
}
public function save(AbstractEntity $entity) {
return $this->mapper->save($entity);
}
public function delete(AbstractEntity $entity) {
return $this->mapper->delete($entity);
}
}
class UserRepository extends AbstractRepository {
// $userMapper property gone
public function __construct(UserMapper $userMapper) {
parent::__construct($userMapper);
}
public function fetchByUsername($username) {
return $this->mapper->fetch( array('username' => $username) );
}
我喜欢第一种方式,因为它UserRepository
拥有UserMapper
.
第二种方式更好,因为代码少但走线
return $this->mapper->fetch( array('username' => $username) );
它并不像
return $this->userMapper->fetch( array('username' => $username) );
当我在用户存储库中时,我知道这$this->mapper
是 a 的一个实例,UserMapper
但我更喜欢像$this->userMapper
.
有没有关于在这种情况下最好做什么的规则?
谢谢。