Filters in CI4 are a great way to control the incoming and outgoing call to controllers.
Filters have two methods before() and after(). The before() method is executed before the controller is called. This allows to view and validate
the incoming data and process accordingly before the controller is called. The class must have both methods present and the function body can be empty.
The best example for filter is the login status check.
You can use filters effectively to check whether the user is in a logged-in status and re-route accordingly.
Step 1 : You have to define the filters in app/Config/Filters.php file.
eg: I have added the line ‘filterlogin’ => \App\Filters\FilterLogin::class
where filterlogin is the name of my filter and \App\Filters\FilterLogin::class is the class.
<?php namespace Config;
use CodeIgniter\Config\BaseConfig;
class Filters extends BaseConfig
{
public $aliases = [
'csrf' => \CodeIgniter\Filters\CSRF::class,
'toolbar' => \CodeIgniter\Filters\DebugToolbar::class,
'honeypot' => \CodeIgniter\Filters\Honeypot::class,
'filterlogin' => \App\Filters\FilterLogin::class
];
}
Step 2 : You can then add the FilterLogin class under the app/Filters folder.
<?php namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
class FilterLogin implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
helper('uri');
if (!session()->get("login_status")) {
return redirect()->to("/login");
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// Do something here
}
}
Here we are checking for a session key login_status. If the value is 0 or the key is not present we can redirect the user to login page.
Hence we need not check for user login at every controller call, filters do that automatically.
Step 3 : Another important page where filters must be mentioned is under app/Config/Routes.php file.
We may not require the filter to be executed at every controller call. Hence we have to mention the filter with its name in the route file.
eg. You want to check the user login status on the checkout page of your website. Then your route call will look as follows.
$routes->get(‘/shop/checkout’, ‘Checkout::show_checkout_page’,[‘filter’ => ‘filterlogin’]);
The application of filters is totally optional and can be used most effectively in the best scenarios.