Skip to content

Add ability to wrap action with middleware #282

@samdark

Description

@samdark

Proposed new feature or change

The idea is to allow non-PSR inputs and outputs for a route:

public function myAction(string $name): array
{
    return ['name' => $name];
}

Not to do it directly in the router, we can allow specifying a middleware that wraps the action, converting PSR inputs to action arguments and action output to PSR output.

https://github.com/yiisoft/router/blob/master/src/Middleware/Router.php#L57

$middlewares = $result->route()->getData('enabledMiddlewares');
$action = array_pop($middlewares);
if ($this->actionWrapper) {
  $middlewares[] = new $this->actionWrapper($action);
}

...

The wrapper itself can be the following:

final class ActionWrapperMiddleware()
{
    public function __construct(private $action)
    {
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $params = $this->getFromRequest($request);
        // TODO: if action is Middleware or has middleware signature, return it as is
        $data = $this->action(...$params);
        $handler->handle(new DataResponse($data));
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions