使用 PHP-DI 实现 Slim:使用 DTO 作为控制器方法参数?

问题描述 投票:0回答:1

我正在使用 PHP Slim Framework V4 构建一个具有

php-di/slim-bridge
的 API,以便在控制器方法中进行依赖项注入。

在 Slim Framework v4 中使用 DTO 处理传入请求时的最佳实践是什么?

我想使用 DTO 来映射和验证请求参数。我可以做:

class TestController
{


    public function index(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $myDto = new BaseDto($request);

        {...}

        return $response;
    }

}

但是我想通过直接将 DTO 注入控制器来存档:

class TestController{

    public function index(BaseDto $myDto): ResponseInterface
    {
        {...}

        return $response;
    }

}

但是由于从 Slim v4 开始,请求不再是 DI 容器的一部分,因此无法解析 BaseDto 的依赖关系,并且出现错误:

cannot be resolved: Entry "Psr\Http\Message\ServerRequestInterface" cannot be resolved: the class is not instantiable

dependency-injection slim dto php-di
1个回答
0
投票

看看https://www.slimframework.com/docs/v4/objects/routing.html#route-strategies

您已经创建了自己的策略,获取路由参数并将其序列化到 DTO 中。您可以使用例如 https://symfony.com/doc/current/components/serializer.html

© www.soinside.com 2019 - 2024. All rights reserved.