php - 在 Slim Framerwork 的容器上设置 $app 实例是一种不好的做法吗?
问题描述
我是新手,在使用Slim 框架创建一个小项目时仍然试图围绕 DI 进行思考。
像这样在容器上设置 $app 是一种不好的做法吗?
$container = $containerBuilder->build();
AppFactory::setContainer($container);
$app = AppFactory::create();
$container->set('app', $app);
我想这样做的原因是有可用的具有 $container 和 $app 实例的抽象类,而不必将其作为构造函数参数传递。为了获取容器实例,我使用了 Slim 文档中的这段代码。
<?php
declare(strict_types=1);
namespace Testing;
use Psr\Container\ContainerInterface;
use Slim\App;
abstract class Service
{
protected ContainerInterface $container;
protected App $app;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
$this->app = $this->container->get('app');
}
}
然后我想像这样实例化扩展 Service 抽象类的类:
$serviceExample = $container->get(ServiceExample::class);
它正在工作,但我觉得我做错了什么,必须有更好的解决方案。如果是这样,你能帮我指出正确的方向吗?
解决方案
如果您使用 DI 容器(和依赖注入),则不应在应用程序类中使用容器或 Slim App 实例,因为这是一种反模式。
相反,您只需要直接在类构造函数中声明所有依赖项,然后让 DI 容器完成其余工作。
<?php
final class MyService
{
private MyRepository $repository;
public function __construct(MyRepository $repository)
{
$this->repository= $repository;
}
}
推荐阅读
- javascript - Axios 419(未知状态)Laravel API csrf 令牌被更改
- python - 如何将文本文件转换为不同的熊猫数据框?
- database - oracle中的程序编译错误
- php - 如何基于 UA 字符串检测基于 Chromium 的浏览器
- c++ - 隐式从 double 转换为 int 时没有精度损失警告
- algorithm - 根据活动、总里程和总时间标准化锻炼
- python - 将用户输入转换为布尔值并在 Python 中引发错误?
- sql - 如何在更新查询中使用 string_split?
- python - 将部分训练的 scikit-learn 模型存储或检查点到磁盘
- c# - 如何修复 System.InvalidOperationException 错误?