'Cannot perform a Redirect within Slim Framework controller __construct()
I have an application in Slim Framework v3. There are 2 controllers, classes/FrontController.php and classes/AdminController.php.
AdminController.php is for Admin functionality (un-surprisingly!) and the FrontController.php for "public" part of the application.
Various routes have been defined in /index.php which run functions in these controllers - all normal.
What I'm trying to do is write a single piece of code (without repeating it all over) inside AdminController::__construct() such that it will redirect users to FrontController::index() if they try and access any Admin routes via URL manipulation.
The code which I have in my AdminController is like this:
public function __construct(Slim\Container $ci) {
$this->ci = $ci;
if (!$this->_isAdmin()) {
return $this->ci->response->withStatus(302)->withHeader('Location', '/index');
}
}
This doesn't seem to do anything even though $this->_isAdmin() returns false - I've even tested it by only returning false irrespective of the result the database would return under normal operation. My expectation is that it would redirect at this point, but it instead goes and loads up AdminController::index() if I try and access /admin in the browser.
I'm guessing this is something to do with the fact that the response cannot be manipulated in the constructor? How can I handle this?
For information the routes in my index.php are like this:
$app->get('/', '\FrontController:index')->setName('/index');
$app->get('/admin', '\AdminController:index');
// many other routes...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
