我试图实现类似于存储库模式的东西。为此,我有一个所有Repos实现的接口和一个所有模型扩展的模型基类。如何在接口中使用多态性?
我从PHP
Fatal error: Declaration of MVCBP\Repositories\UserRepository::add() must be compatible with MVCBP\Core\RepositoryInterface::add(MVCBP\Core\Model $model) in D:\wamp\www\mvc\MVCBP\Repositories\UserRepository.php on line 9
以下错误消息我想的是,我在仓库类中的方法应根据接口接受模型的实例作为参数。不过,我想在实现中键入提示特定的模型。这在PHP中可行吗?
RepositoryInterface.php
<?php
namespace MVCBP\Core;
use MVCBP\Core\ModelInterface;
interface RepositoryInterface
{
public function add(ModelInterface $model);
}
UserRepository.php
<?php
namespace MVCBP\Repositories;
use MVCBP\Core\PDOMySQL;
use MVCBP\Core\RepositoryInterface;
use MVCBP\Models\User;
class UserRepository extends PDOMySQL implements RepositoryInterface
{
public function add(User $user)
{
//Omitted
}
//Omitted
}
ModelInterface.php
<?php
namespace MVCBP\Core;
interface ModelInterface {}
user.php的
<?php
namespace MVCBP\Models;
use MVCBP\Core\ModelInterface;
use MVCBP\Core\Validate;
use MVCBP\Repositories\UserRepository;
require_once(__DIR__ . '/../lib/password.php');
class User implements ModelInterface
{
//Omitted
}
为什么你认为模型是一类? –