首页 > 解决方案 > 在 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);

它正在工作,但我觉得我做错了什么,必须有更好的解决方案。如果是这样,你能帮我指出正确的方向吗?

标签: phpdependency-injectionslimphp-di

解决方案


如果您使用 DI 容器(和依赖注入),则不应在应用程序类中使用容器或 Slim App 实例,因为这是一种反模式。

相反,您只需要直接在类构造函数中声明所有依赖项,然后让 DI 容器完成其余工作。

<?php

final class MyService
{
    private MyRepository $repository;

    public function __construct(MyRepository $repository)
    {
        $this->repository= $repository;
    }

}

推荐阅读