Slim默认带有
Pimple.一些开发人员认为(并且我倾向于同意这些),Pimple不是依赖注入容器,而是服务定位器,因为它不能自己解决依赖关系,需要注册它们.
Slim 3适用于任何实现Container interop interface的依赖管理器,PHP-DI就是这样做的.
转到this package.这就是我用于我的项目,它简直太棒了,因为autowiring.简而言之,PHP-DI读取类的构造函数并理解需要注入的内容,儿子你没有像使用Pimple一样注册依赖项.
有时我认为(希望?)PHP-DI将取代Pimple作为Slim的默认DI容器,因为它更简单.
以下是您对Pimple的处理方式:
namespace Controllers;
class UsersController
{
// Inject Container in controller (which is bad, actually)
public function __construct(ContainerInterface $container)
{
// grab instance from container
$this->repository = $container['userRepository'];
}
// Handler of a route
public function getAllUsers($request, $response)
{
$user = $this->repository->getAllUsers();
return $response->withJson($users);
}
}
这是与PHP-DI相同的控制器:
namespace Controllers;
class UsersController
{
// Declare your dependencies in constructor:
// PHP-DI will find the classes and inject them automatically
public function __construct(UserRepository $repository)
{
$this->repository = $repository;
}
// Handler of a route
public function getAllUsers($request, $response)
{
$user = $this->repository->getAllUsers();
return $response->withJson($users);
}
}
The problem with this is, if I have say 100 classes, do I have to pass
(or inject) the container 100 times? That seems really, really
tedious.
如果您使用与PHP-DI捆绑在一起的Slim,则问题会通过自动装配自动解决. 🙂