Welcome Guest, Not a member yet? Register   Sign In
how to use controllers filters on CI4
#2

Filters are simply classes that implement FilterInterface, as you said. They have very few jobs. For before filters, they can modify the Request on the way in or, return a Response, like with a redirect() call. After filters can modify the Response before it's sent to the client, and will likely be used significantly less than before filters.

Due to the beauty of namespaces, the files themselves can live anywhere you want them to. An easy solution, and the one that the built in filters use, is to place the file at application/Filters/{your_file}.php. The class would then be in the App\Filters namespace. So, a simple access check like you're talking about might be something like this:

Code:
// File: application/Filters/Auth.php
<?php namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class AuthFilter implements FilterInterface
{
   public function before(RequestInterface $request)
   {
       $auth = service('auth');

       if (! $auth->isLoggedIn())
       {
           return redirect('login');
       }
   }
   
   public function after(RequestInterface $request, ResponseInterface $response)
   {
       
   }  
   
}

What this does is it uses a custom Auth service which simply loads up an Auth class. It then checks if the user is logged in. If they are then nothing happens. The next filter is ran, or the controller is fired up. If, however, they're not logged in, then it returns a redirect response and script execution stops right there, the user is redirected and asked to log in. In the before/after methods you can put any logic you need to check. They should usually be fairly small, simple classes like this that can come up with a yes/no answer.

Your controllers don't know about filters, and don't care. If you've modified the Request object, then they'll get that. Otherwise, they are completely ignorant. Once you've created the class, you just need to configure it in application/Config/Filters.php. The docs will guide you through that. If you have specific questions about that process, feel free to ask.

This example, by the way, was ripped directly from the user guide. Make sure to read that page over a few times, and look at the existing ones.
Reply


Messages In This Thread
how to use controllers filters on CI4 - by casa - 01-10-2017, 02:46 PM
RE: how to use controllers filters on CI4 - by kilishan - 01-10-2017, 08:53 PM



Theme © iAndrew 2016 - Forum software by © MyBB