Tobia
Tobia

Reputation: 9506

Slim Framework middleware that selects a route

How to select a route in a custom Slim middleware? I would like to force a specific route, but I don't know how to do:

class Acl extends \Slim\Middleware{
    public function call()
    {
        if($isnotlogged){
            //force to select "login" route
            ...
        }
        $this->next->call();
    }   
}

Upvotes: 0

Views: 699

Answers (1)

Tobia
Tobia

Reputation: 9506

This seems to be a working hack:

\Slim\Router $matchedRoutes property has a protected visibility, so I must create a custom Router to override it:

class MyRouter extends \Slim\Router {

    public function setRoute(\Slim\Route $route){
        $this->matchedRoutes=[$route];
    }

}

When I initialize Slim I have to set my Router:

$app = new \Slim\Slim();
$app->router=new MyRouter();

Finally I can force the route selection inside my middleware:

class Acl extends \Slim\Middleware{
    public function call()
    {
        if($isnotlogged){
            $this->getApplication()->router()->setRoute($this->getApplication()->router->getNamedRoute("login"));
        }
        $this->next->call();
    }   
}

Upvotes: 2

Related Questions