0

开门见山。

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.

有没有关于在这种情况下最好做什么的规则?

谢谢。

4

1 回答 1

1

您的第一种方法没有意义......您正在复制代码。

您必须了解的是,它UserRepository仍然具有$mapper属性。它只是不能直接访问,因为它是private. 您需要访问器方法来执行此操作:

abstract class AbstractRepository {

    // Different visibility
    private $mapper;

    public function __construct(AbstractMapper $mapper) {
        $this->mapper = $mapper;
    }

    protected function getMapper() {
        return $this->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->getMapper()->fetch( array('username' => $username) );

}

通过这种方式,您可以确保任何子*Repository类都会对 进行任何奇怪的操作$mapper,但您仍然可以使用getMapper.

您的第二种方法也是正确的,但限制较少。

于 2013-11-07T21:49:22.487 回答