01-21-2021, 06:00 PM
I'm migrating an extensive site to CI4. I organize my controllers thusly:
* public ones that just extend BaseController
* ones for that require authenticated users which extend UserController
* admin-only pages that extend AdminController, which extends UserController and does extra permission checks on a db table.
The old CI3 redirect() function was great because you could call it anywhere. Sadly, the new approach does not work in either my __construct function or in initController function:
What is the recommended best practice if I want to redirect from inside a __construct or initController function? Someone suggested setting up filters or some kind but that isn't going to work for me.
* public ones that just extend BaseController
* ones for that require authenticated users which extend UserController
* admin-only pages that extend AdminController, which extends UserController and does extra permission checks on a db table.
The old CI3 redirect() function was great because you could call it anywhere. Sadly, the new approach does not work in either my __construct function or in initController function:
PHP Code:
class AdminController extends BaseController
{
function __construct()
{
// CI4's controller class doesn't have a constructor, but ours currently
// has a trivial one as a stub
parent::__construct();
}
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
// if the user is not logged in, remember what page they requested and redirect them to the login page
// once they log in, they will be redirected back to the requested url
if (!$this->user_logged_in()) {
$_SESSION[self::SESSION_KEY_LOGIN_REDIRECT_URL] = $_SERVER["REQUEST_URI"];
// THIS DOES NOT WORK
return redirect()->to("/login");
}
// this code never even runs if the user isn't logged in
if (!$this->has_permission("VIEW_ADMIN_MENU")) {
show_error("You are not permitted to view this page", 403);
}
} // initController()
} // class AdminController
What is the recommended best practice if I want to redirect from inside a __construct or initController function? Someone suggested setting up filters or some kind but that isn't going to work for me.