In CodeIgniter 4, you can define filters for your controllers to process incoming requests before they reach the controller methods. Filters are useful for tasks such as input validation, authentication, or authorization. To exclude specific controller methods from being filtered, you can use the except
property when defining the filters.
Here's how you can define filters with exceptions in CodeIgniter 4:
- Create a Filter:
Filters in CodeIgniter 4 are defined as PHP classes. Create a new filter class that extends the
CodeIgniter\Filters\Filter
base class. Inside the filter class, implement thebefore
method, which will be executed before the controller method.
php// app/Filters/MyFilter.php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
class MyFilter implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
// Your filtering logic here
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// Optional, logic to be executed after the controller method
}
}
- Register the Filter: After creating the filter class, you need to register it in the application's configuration.
php// app/Config/Filters.php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Filters extends BaseConfig
{
public $aliases = [
'myfilter' => \App\Filters\MyFilter::class,
];
public $globals = [
'before' => [
'myfilter', // Apply this filter to all routes before the controller method
],
'after' => [
// Add any filters to be applied after the controller method (if needed)
],
];
public $filters = [
'myfilter' => [
'except' => [
'controllerMethod1',
'controllerMethod2',
// Add the names of controller methods to exclude from filtering
],
],
];
}
In this example, we registered the MyFilter
class as myfilter
and applied it globally to all routes before the controller method. However, we also specified the except
property for the myfilter
, providing an array of controller method names that should be excluded from this filter.
Now, the MyFilter
filter will be applied to all controller methods except those specified in the except
array.
Please ensure that the filter class and the configuration file are correctly placed in their respective directories as shown in the examples above.