【问题标题】:Slim (V3) Framework: Add a prefix to generated links, but not to incoming routesSlim (V3) 框架:为生成的链接添加前缀,但不为传入路由添加前缀
【发布时间】:2019-06-28 22:15:41
【问题描述】:
【问题讨论】:
标签:
php
proxy
routes
slim
prefix
【解决方案1】:
类Slim\Router 似乎有一个basePath,可以通过调用setBasePath 来设置,但似乎这个basePath 在你的情况下没有用。您可以拥有自己的 Router 类,并使用自定义 pathFor 方法为命名路由生成的路径添加前缀,然后您可以将 Slim 的默认 router 替换为您的。这是一个功能齐全的示例:
// 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();
如果您访问<your-domain>/sample,输出将是:
From request: /sample
Generated by pathFor: /some/prefix/to/be/removed/by/proxy/sample