我喜欢 Unity 和 Ninject 框架,将 C#.NET 的依赖注入到具有存储库接口等的控制器中,但我正在尝试在 PHP 中寻找替代方案并且正在苦苦挣扎。
我有:
class User
{
//..
}
interface IUserRepository
{
public function Repository(); // This can't work as a variable, should I abstract?
}
class UserRepository implements IUserRepository
{
public function Repository()
{
$users = // DAO gets users and returns them..
// But how does the IUserRepository help me at all? Even if I had ninject or
// Unity creating some new link between the UserRepo and IUserRepo?
return $users;
}
public function GetAllUsers()
{
// errr.. I'm confused
}
}
// Something has to say if the AdminController is called,
// inject into its construct, a new IUserRepository
class AdminController extends Controller
{
private $repository;
public function __Construct( $repository )
{
$this->repository = $repository;
}
public function ActionResult_ListUsers()
{
$users = $repository->GetAllUsers();
// Do some clever View method thing with $users as the model
}
}
真正的问题是 PHP 和存储库方法。这是如何运作的?你可以看到我有点弄脏了,真的很想把它弄好!
编辑::
更简单的问题。interface关键字有什么好处?当您无法创建一个像类那样的新接口,然后用定义它们的正确类填充时,如何声明一个带有一些未定义方法的接口,然后创建一个实现这些方法的新类来扩展它们?