【问题标题】:Change route files based upon URI path in Slim 3在 Slim 3 中根据 URI 路径更改路由文件
【发布时间】:2016-11-22 02:10:51
【问题描述】:

好的,所以我有 4 个文件夹,它们都有自己的 route.php。所以我想根据uri路径要求每个文件夹的路径。例如,如果我的网站路径是 www.example.com/user,那么 Slim 框架将需要控制器/用户/路由的路径。我正在尝试使用中间件来实现这一点,但是当我测试它时,我得到一个“调用成员函数错误”,那么我该如何解决这个问题。

下面是我的代码:

 //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;
});

因此,在框架确定路由之前,然后添加所需的路径。但是有些东西运行不正常,有什么想法吗?

【问题讨论】:

  • 你为什么要这样做?
  • 保持路线分开,只在索引中加载路线页面,这样它就可以运行得更快..或者我看的不对?
  • 那不会有太大区别。

标签: php html slim slim-lang slim-3


【解决方案1】:

您不应该这样做,因为注册所有路线不会花费太多时间。

但是,如果您想这样做,您需要对您的代码进行一些更改:

  1. $request->getAttribute('route')不返回路径,返回slim的路由对象

    如果您想使用路径,请改用$request->getUri()->getPath()(它不以/ 开头,所以路由 f.ex 是(/customRoute/test 它返回customRoute/test

  2. 你需要使用$app,因为$this是Pimple的ContainerInterface,而不是slim的App

  3. 确保您没有在设置中将 determineRouteBeforeAppMiddleware 设置为 true,因为它会在中间件执行之前检查要执行的路由。

这是一个运行示例:

$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();

【讨论】:

  • This article 声称添加额外的路由会增加加载时间。
猜你喜欢
  • 2020-12-30
  • 1970-01-01
  • 2017-11-19
  • 2013-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多