我想檢查用戶是否登錄。因此,我有一個Class類,返回true或false。現在我想一箇中間件,如果用戶登錄,檢查。Slim 3中間件重定向
$app->get('/login', '\Controller\AccountController:loginGet')->add(Auth::class)->setName('login');
$app->post('/login', '\Controller\AccountController:loginPost')->add(Auth::class);
驗證類
class Auth {
protected $ci;
private $account;
//Constructor
public function __construct(ContainerInterface $ci) {
$this->ci = $ci;
$this->account = new \Account($this->ci);
}
public function __invoke($request, \Slim\Http\Response $response, $next) {
if($this->account->login_check()) {
$response = $next($request, $response);
return $response;
} else {
//Redirect to Homepage
}
}
}
因此,當用戶在頁面登錄將呈現正確。但是當用戶沒有被自動識別時,我想重定向到主頁。但是怎麼樣?!
$response->withRedirect($router->pathFor('home');
這不行!
該解決方案是行不通的 – Vashtamyty
從中間件中提供的代碼,這是行不通的。 – systemovich
在OP的情況下,他們沒有在使用它之前定義'$ router'變量。假設你的中間件沒有從另一個類繼承,你在哪裏定義'$ this-> router'? –