具有相同签名的多个Slim路由

时间:2016-01-20 10:25:40

标签: slim slim-3

我们正在考虑使用Slim 3作为API的框架。我搜索了SO和Slim文档,但找不到问题的答案。如果我们有不同的路由文件(例如v1,v2等),并且两条路由具有相同的签名,则会引发错误。有没有办法级联路由,以便使用特定签名的最后加载路由?

例如,假设v1.php有GET ("/test")的路由,v2.php也包含此路由,我们可以使用最新版本吗?更简单的是,如果一个路由文件包含两个具有相同签名的路由,是否有一种方法可以使用后一种方法(并且不会抛出错误)?

类似的问题被问到here但是它使用了钩子(根据here已经从Slim 3中删除了)

1 个答案:

答案 0 :(得分:4)

我查看了Slim代码,但我找不到允许重复路由的简单方法(防止异常)。 新的Slim使用FastRoute作为依赖。它调用FastRoute\simpleDispatcher并且不提供任何配置可能性。即使它确实允许某些配置,FastRoute也没有任何内置选项允许重复路由。

但是按照上面的说明,我们可以通过向Slim App传递自定义DataGenerator来获取自定义DataGenerator,该自定义Router会实例化一些FastRoute::Dispatcher implementation,然后使用自定义DataGenerator

首先CustomDataGenerator(让我们轻松一点,从\FastRoute\RegexBasedAbstract\FastRoute\GroupCountBased进行一些复制和粘贴)

class CustomDataGenerator implements \FastRoute\DataGenerator {
    /*
     * 1. Copy over everything from the RegexBasedAbstract
     * 2. Replace abstract methods with implementations from GroupCountBased
     * 3. change the addStaticRoute and addVariableRoute
     * to the following implementations
     */
    private function addStaticRoute($httpMethod, $routeData, $handler) {
        $routeStr = $routeData[0];

        if (isset($this->methodToRegexToRoutesMap[$httpMethod])) {
            foreach ($this->methodToRegexToRoutesMap[$httpMethod] as $route) {
                if ($route->matches($routeStr)) {
                    throw new BadRouteException(sprintf(
                        'Static route "%s" is shadowed by previously defined variable route "%s" for method "%s"',
                        $routeStr, $route->regex, $httpMethod
                    ));
                }
            }
        }
        if (isset($this->staticRoutes[$httpMethod][$routeStr])) {
            unset($this->staticRoutes[$httpMethod][$routeStr]);
        }
        $this->staticRoutes[$httpMethod][$routeStr] = $handler;
    }
    private function addVariableRoute($httpMethod, $routeData, $handler) {
        list($regex, $variables) = $this->buildRegexForRoute($routeData);
        if (isset($this->methodToRegexToRoutesMap[$httpMethod][$regex])) {
            unset($this->methodToRegexToRoutesMap[$httpMethod][$regex]);
        }
        $this->methodToRegexToRoutesMap[$httpMethod][$regex] = new \FastRoute\Route(
            $httpMethod, $handler, $regex, $variables
        );
    }
}

然后是自定义Router

class CustomRouter extends \Slim\Router {
    protected function createDispatcher() {
        return $this->dispatcher ?: \FastRoute\simpleDispatcher(function (\FastRoute\RouteCollector $r) {
            foreach ($this->getRoutes() as $route) {
                $r->addRoute($route->getMethods(), $route->getPattern(), $route->getIdentifier());
            }
        }, [
            'routeParser' => $this->routeParser,
            'dataGenerator' => new CustomDataGenerator()
        ]);
    }
}

最后使用自定义路由器

实例化Slim应用程序
$app = new \Slim\App(array(
    'router' => new CustomRouter()
));

上面的代码,如果检测到重复路由,则删除先前的路由并存储新路由。

我希望我没有错过任何更简单的方法来实现这一结果。

相关问题