Skip to content

[4.x] Decorated Response in case of explicitly set Response Factory #2709

Description

@adriansuter

Hi there

The problem

When providing a response factory explicitly to the AppFactory::create() method, then the response would no longer be decorated automatically. Is this the expected behaviour?

Say my index.php is as follows (I am using the Nyholm PSR-7 for this example):

declare(strict_types=1);

use Nyholm\Psr7\Factory\Psr17Factory;
use Psr\Http\Message\RequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Slim\Factory\AppFactory;

require __DIR__.'/../vendor/autoload.php';

// Explicitly define the response factory!!
$app = AppFactory::create(
    new Psr17Factory()
);

$app->get('/', function (Request $request, Response $response, array $args) {
    $response->getBody()->write(get_class($request).', '.get_class($response));

    return $response;
});

$app->run();

Calling the route returns

Slim\Http\ServerRequest, Nyholm\Psr7\Response

So the request gets decorated (as expected), but the response does not get decorated.

Is this the correct solution?

In order to get the response decorated, we need to do as follows, right?

declare(strict_types=1);

use Nyholm\Psr7\Factory\Psr17Factory;
use Psr\Http\Message\RequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Slim\Factory\AppFactory;
use Slim\Factory\Psr17\SlimHttpPsr17Factory;

require __DIR__.'/../vendor/autoload.php';

$responseFactory = new Psr17Factory();
$app = AppFactory::create(
    SlimHttpPsr17Factory::createDecoratedResponseFactory(
        $responseFactory, $responseFactory
    )
);

$app->get('/', function (Request $request, Response $response, array $args) {
    $response->getBody()->write(get_class($request).', '.get_class($response));

    return $response;
});

$app->run();

The result was

Slim\Http\ServerRequest, Slim\Http\Response

If this is the way to go, then this should be mentioned in the documentation I guess. What do you think?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions