2016-11-21 113 views
0

好吧,所以我有4個文件夾都有自己的route.php。所以我想要求基於uri路徑的每個文件夾的路徑。例如,如果我的網站路徑是www.example.com/user,那麼Slim框架將需要控制器/用戶/路徑的路徑。我試圖用中間件來實現這一點,但是當我測試它時,我得到了「調用成員函數錯誤」,所以我該如何解決這個問題。根據修改3中的URI路徑更改路由文件

這裏是我下面的代碼:

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

所以任何事情之前的框架決定路徑,然後添加所需的路徑。但有些東西不正常,有什麼想法?

+0

你爲什麼要這麼做? – jmattheis

+0

保持路由分離,只加載索引中的路由頁面,以便它可以運行得更快..或我不正確的方式嗎? –

+0

這不會有太大的區別。 – jmattheis

回答

0

那麼你不應該這樣做,因爲它不應該花很多時間來註冊所有路線。

但如果你想待辦事項這個你剷除作出一些改變,以找你的代碼:

  1. $request->getAttribute('route')沒有返回路徑,它返回的苗條

    路由對象如果要使用的路徑中使用$request->getUri()->getPath()代替(但不以/開始這樣的路線f.ex是(/customRoute/test返回customRoute/test

  2. 您需要使用$app在這種情況下$this是疙瘩ContainerInterface而不是苗條

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