Skip to content

Filters

Hüseyin Akbaş edited this page Jan 30, 2018 · 1 revision

Filters are generally known Middlewares in most frameworks but the structure they have is named them as filters. They are generally used to control or restrict some request before the real action is performed.

They can be found and defined under app/filters directory and defined as FooFilter.php

A filter should have at least two functions in order to process correctly. The first one is the handle function. It should return a boolean value and if it's true, the real action can work. If false, then, the fallback action in the filter is called to compensate.

A simple example of Filter can be like this:

<?php

class AuthFilter extends Filter{

  public function handle(){
    return Auth::check(); 
  }
  
  public function fallback(){
	  redirect('/');
  }
}

AuthFilter is handling the authorization by calling the check function which returns boolean if true, it passes. Otherwise, the fallback works and redirect functions sends the client to the / route.

After we defined or add premade ones, we use filter in controller's beforeAction method. Each controller has functions filterOnly, filterExcept and filter functions.

filterOnly

It is used to filter certain actions within the controller. It takes two parameters. The first parameter is used to send filter name, the second is should be an array of the actions filtered. Example code can be like this:

<?php

use Just\Core\Controller;

class AuthController extends Controller{
    public function beforeAction(){
      $this->filterOnly('AuthFilter', ['getIndex'])
    }

    public function getIndex(){
      //...
    }
    //...
}

filterExcept

This filtering function is used to filter all actions except the list given. It takes two parameters one is to give filter name, the other one is to give an array of the actions is not filtered.

An example code can be like:

<?php

use Just\Core\Controller;

class AuthController extends Controller{
    public function beforeAction(){
      $this->filterExcept('AuthFilter', ['getLogin'])
    }

    public function getIndex(){
      //...
    }
    public function getLogin(){
      //...
    }
    //...
}

Here getLogin is not filtered but all the other actions like getIndex is filtered by the AuthFilter.

filter

The last one is the filter function and it takes only one parameter. Its aim is to filter all actions given in controller.

Example usage:

<?php

use Just\Core\Controller;

class AuthController extends Controller{
    public function beforeAction(){
      $this->filter('AuthFilter')
    }

    public function postDelete(){
      //...
    }
    public function postInsert(){
      //...
    }
    //...
}

This function is filtering all the functions like postDelete, postInsert in the controller by AuthFilter.

Clone this wiki locally