简体   繁体   中英

Slim (V3) Framework: Add a prefix to generated links, but not to incoming routes

I have basically this exact question Add a prefix to generated links, but not to incoming routes but for Slim V3. The short version of the question is:

How can I add a prefix to generated links (eg those generated with $router->pathFor('home'), say) but NOT include this prefix as part of the routing.

In my situation I have a front-end proxy which is responsible for routing to my application in a Docker container (although how that is set up is irrelevant).

I need the links that are ultimately sent back to the browser to include the prefix, but for them to be ignored in the routes as the proxy server removes them when it does the passthrough.

Class Slim\\Router seems to have a basePath which could be set by calling setBasePath , but it seems this basePath is not useful in your case. You can have your own Router class with a custom pathFor method capable of prefixing your paths generated for a named route, then you can replace Slim's default router with yours. Here is a fully functional example:

// declare your class and change pathFor behavior
class MyPrefixAwareRouter extends Slim\Router {
    private $prefix = '';
    public function setPrefix($prefix = '') {
        $this->prefix = $prefix;
    }
    public function pathFor($name, array $data = [], array $queryParams = [])
    {
        return $this->prefix . parent::pathFor($name, $data, $queryParams);
    }
}

$container = new Slim\Container;

// custom path prefix for all named routes
$container['route-prefix'] = '/some/prefix/to/be/removed/by/proxy';

// router setup, copied from Slim\DefaultServicesProvider.php
// with slight change to call setPrefix
$container['router'] = function ($container) {
    $routerCacheFile = false;
    if (isset($container->get('settings')['routerCacheFile'])) {
        $routerCacheFile = $container->get('settings')['routerCacheFile'];
    }
    $router = (new MyPrefixAwareRouter)->setCacheFile($routerCacheFile);
    if (method_exists($router, 'setContainer')) {
        $router->setContainer($container);
    }
    $router->setPrefix($container->get('route-prefix'));

    return $router;
};
$app = new \Slim\App($container);

$app->get('/sample', function($request, $response, $args){
    return "From request: " . $request->getUri()->getPath() . "\nGenerated by pathFor: " . $this->router->pathFor('sample-route');
})->setName('sample-route');
// Run app
$app->run();

If you visit <your-domain>/sample the output will be:

From request: /sample
Generated by pathFor: /some/prefix/to/be/removed/by/proxy/sample

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM