Search code examples
phphtmlslimslim-langslim-3

Change route files based upon URI path in Slim 3


Ok so I have 4 folders all which have their own route.php. So I would like to require the path to each folder based upon the uri path. So for example, if my website path is www.example.com/user then the Slim framework would require the path to controller/users/routes. I'm trying to achiee this using middleware but when I test it I get a "Call to a member function error" so how do I fix this.

Here is my code below:

 //determine the uri path then add route path based upon uri
$app->add(function (Request $request, Response $response, $next) {
    if (strpos($request->getAttribute('route'), "/user") === 0) {
        require_once('controllers/users/routes.php');
    } elseif (strpos($request->getUri()->getPath(), "/public") === 0) {
        require_once('controllers/public/routes.php');
    } elseif (strpos($request->getUri()->getPath(), "/brand") === 0) {
        require_once('controllers/brands/routes.php');
    }elseif (strpos($request->getUri()->getPath(), "/admin") === 0) {
        require_once('controllers/admin/routes.php');
    }elseif (strpos($request->getUri()->getPath(), "/") === 0) {
        require_once('routes.php');
    }

    $response = $next($request, $response);
    return $response;
});

So before anything the framework determines the route then adds the required path. But something is not functioning right, any ideas?


Solution

  • Well you shouldn't do this because it shouldn't take much time to register all routes.

    But if you want todo this you weed to make some changes to you'r code:

    1. $request->getAttribute('route') doesn't return the path, it returns the route object of slim

      If you want to use the path use $request->getUri()->getPath() instead (it doesn't start with a / so the route f.ex is (/customRoute/test it returns customRoute/test

    2. You need to use the $app as $this in this context is the ContainerInterface from Pimple and not the App of slim

    3. Make sure you didn't set determineRouteBeforeAppMiddleware inside the settings to true as it checks which route to execute before the middleware execution.

    Here a running example:

    $app = new \Slim\App();
    $app->add(function($req, $res, $next) use ($app) {
        if(strpos($req->getUri()->getPath(), "customPath" ) === 0) {
            $app->get('/customPath/test', function ($req, $res, $arg) {
                return $res->write("WUII");
            });
        }
        return $next($req, $res);
    });
    $app->run();