Slim with PHP-DI: Using a DTO as controller method parameter?

257 Views Asked by At

I'm using the PHP Slim Framework V4 to build an API with php-di/slim-bridge to have dependency injection within the controller methods.

What's the best practice when working with DTOs for incoming requests in Slim Framework v4?

I'd like to use DTOs to map and validate request parameters. I could do:

class TestController
{


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

        {...}

        return $response;
    }

}

However I'd like to archive this by directly injecting the DTO into the Controller:

class TestController{

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

        return $response;
    }

}

But because as of Slim v4, the request is no longer part of the DI container, the dependency of the BaseDto cannot be resolved and I get the error:
cannot be resolved: Entry "Psr\Http\Message\ServerRequestInterface" cannot be resolved: the class is not instantiable

1

There are 1 best solutions below

0
Gabor On

the dependency of the BaseDto cannot be resolved

I don't think that DTO's should have dependencies

Containers can't resolve Interfaces, because they're not instantiatable and multiple classes can implement the same interface so the container wouldn't know which one you actually need. You have to manually map the interface to a class, see: https://php-di.org/doc/php-definitions.html#syntax