Can I set the route action handler (some controller and action or action class) from the middleware?
Yes, you can. You can do something like if the route was not determined:
use Interop\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Route;
class MidTest
{
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function __invoke(
ServerRequestInterface $requestInterface,
ResponseInterface $response,
callable $next
) {
/** @var Route $route */
$route = $this->container->get('router')->getNamedRoute('routeName');
$route->setCallable('new callable here');
return $next($requestInterface, $response);
}
}
And set the route name like:
use \Slim\Http\Request;
use \Slim\Http\Response;
$app->add('\App\Middleware\MidTest');
$app->get('/', function (Request $request, Response $response, $args) {
//something
})->setName('routeName');
If the route is determined, you can get the actual route from middleware with:
/** @var Route $route */
$route = $request->getAttribute('route');
$route->setCallable('new callable here');
Looks like this is resolved; going to close.
Very well resolved. Thx! Please, tell me if creating a question in StackOverflow to document this would be nice.
Most helpful comment
Yes, you can. You can do something like if the route was not determined:
And set the route name like:
If the route is determined, you can get the actual route from middleware with: