我正在尝试在 PHP 中实现非常基本的存储库模式。
假设我需要一个通用接口来处理通用实体存储:
<?php
interface IRepository
{
public function persist(Entity $entity);
// reduced code for brevity
}
现在我建立实体类型层次结构:
<?php
abstract class Entity
{
protected $id;
protected function getId()
{
return $this->id;
}
}
这是 Post 类:
<?php
class Post extends Entity
{
private $title;
private $body;
}
现在我想使用 PDO 支持的数据库来存储帖子:
<?php
use PDO;
abstract class DatabaseRepository implements IRepository
{
protected $pdo;
protected $statement;
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
}
现在我尝试实现 IRepository 接口
<?php
class PostRepository extends DatabaseRepository
{
// I have an error here
// Fatal error: Declaration of PostRepository::persist(Post $post) must be compatible with IRepository::persist(Entity $entity)
public function persist(Post $post)
{
}
}
如您所见,这会引发致命错误。在 PostRepository::persist() 中使用类型提示我保证我使用 Entity 子对象来满足 IRepository 的要求。那么为什么会抛出这个错误呢?