0

好的,所以我有 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;
});

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

4

1 回答 1

0

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

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

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

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

  2. 在这种情况下,您需要使用$appas来自 Pimple 而不是 slim 的 App$thisContainerInterface

  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();
于 2016-11-21T18:10:51.637 回答