How access Request object on DI Container?

I need to get request headers in a dependency of container. I’m using PHP-DI with Slim-Bridge.

// PHP-DI definitions file

return [
    UrlGenerator::class => function () {
        // how get $request outside of a route?
        return new UrlGenerator($request);

The request and response objects are context-specific and were removed from the container in Slim 4.

To implement a UrlGenerator you could pass the $request object to the UrlGenerator instance via setRequest method.

Example Middleware


namespace App\Middleware;

use App\Factory\UrlBuilder ;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

final class UrlBuilderMiddlware implements MiddlewareInterface
     * @var UrlBuilder 
    private $urlBuilder ;

    public function __construct(UrlBuilder $urlBuilder)
        $this->urlBuilder= $urlBuilder;

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface

        return $handler->handle($request);
1 Like

Thanks :slight_smile: