php framework注入,php – Slim Framework中的依赖注入 – 将Container传递给您自己的类...

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,则问题会通过自动装配自动解决. 🙂

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值