0

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();
    }   
}
Tobia
  • 9,165
  • 28
  • 114
  • 219
  • I'd have thought the routing was already chosen at this point. Can you do a redirect instead, or do you particularly want to do an internal forwarding? (Have used Slim, but don't know whether this is possible). – halfer Jan 19 '15 at 14:36
  • Possibly related: http://stackoverflow.com/questions/21881963/slim-php-only-catch-valid-routes-with-middleware – halfer Jan 19 '15 at 14:38
  • I can not redirect because I'm not inside a callback (http://stackoverflow.com/questions/19654370/slim-php-halt-method-behaves-differently-than-documented). Route seems to be select on the last middleware call (Slim itself), I want to force the selection of the route – Tobia Jan 19 '15 at 14:51
  • [This example](http://stackoverflow.com/a/25110369/472495) appears to dispatch a custom route - worth a look? – halfer Jan 19 '15 at 14:59
  • 1
    I found another solution, but I had to change a visibility of a \Slim\Router property – Tobia Jan 19 '15 at 15:06

1 Answers1

2

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();
    }   
}
Tobia
  • 9,165
  • 28
  • 114
  • 219