我在Slim Framework v3中有一個應用程序。有2個控制器,classes/FrontController.php
和classes/AdminController.php
。在Slim Framework控制器中無法執行重定向__construct()
AdminController.php
適用於管理功能(出人意料!)和FrontController.php
適用於應用程序的「公共」部分。
在/index.php
中定義了各種路由,它們在這些控制器中運行功能 - 都是正常的。
我想要做的是在AdminController::__construct()
的內部編寫一段代碼(無需重複遍歷),以便在用戶通過URL操作嘗試訪問任何管理路由時將用戶重定向到FrontController::index()
。
,我有我的AdminController的代碼是這樣的:
public function __construct(Slim\Container $ci) {
$this->ci = $ci;
if (!$this->_isAdmin()) {
return $this->ci->response->withStatus(302)->withHeader('Location', '/index');
}
}
這似乎並沒有做任何事情,即使$this->_isAdmin()
返回false - 我甚至通過只測試它返回false不管數據庫在正常操作下返回的結果。我的期望是,它會在這個時候重定向,但是如果我嘗試在瀏覽器中訪問/admin
,它會加載AdminController::index()
。
我猜這是與響應無法在構造函數中操作的事實?但我現在迷失了,不知道該如何處理。任何意見讚賞。
的信息在我index.php
的路線是這樣的:
$app->get('/', '\FrontController:index')->setName('/index');
$app->get('/admin', '\AdminController:index');
// many other routes...
雖然使用上面的方法,你可能必須添加一個類似的東西*每個*路線?因此,在每個路由方法中添加邏輯沒有什麼優勢?這當然不是很乾! – Andy
@Andy你可以使用分組路由參見[Slim3的路由器](https://www.slimframework.com/docs/objects/router.html)搜索「路由組」,在那裏你可以添加中間件到組中,然後你不需要把它添加到每條路線。你也可以添加一個全局中間件,然後檢查起始URL'/ admin'。或者您可以添加一個自己的[錯誤處理程序](https://www.slimframework.com/docs/handlers/error.html)並拋出一個拒絕訪問異常並將其捕獲。 – jmattheis