Skip to main content

Filter

Filters are controllers that are executed before the main controller. They allow you to monitor and influence web applications.

Registering Filters​

Filters do not differ in their structure from main controllers, but several filters can be executed per request. So you could also register several filters for the same context path.

[routing]

filters[] = "/example > atusch\filter\ExampleFilter"
filters[] = "/example > atusch\filter\SomeOtherFilter"

Just like main controllers, filters usually extend n2n\web\http\controller\ControllerAdapter.

class ExampleFilter extends ControllerAdapter {

public function doFoo(array $params) {
if ($params[0] == 'baz' && '127.0.0.1' != $this->getRequest()->getRemoteIp()) {
throw new ForbiddenException();
}
}
}

The filter above ensures that http://[url-to-n2n-public]/example/foo/baz/... can only be accessed from the local machine.

Controlling Plan​

n2n creates an n2n\web\http\controller\ControllingPlan for every request, which you can access via ControllerAdapter::getControllingPlan(). The controlling plan contains the filters and the main controller that are to be executed for the current request. The controlling plan can be modified at runtime, which can be particularly useful in filters. Via ControllingPlan::abort() you can, for example, abort the execution of the controlling plan.

For example, if you want to protect an area http://[url-to-n2n-public]/secure/... with access control, you could register a filter for it:

[routing]

filters[] = "/secure/** > atusch\filter\AuthorizationFilter"

The following example shows you how you could implement such a filter:

class AuthorizationFilter extends ControllerAdapter {

public function index(LoginContext $loginContext) {
if ($loginContext->hasUser()) {
return;
}

$this->forward('view\login.html', array('loginContext' => $loginContext));
$this->getControllingPlan()->abort();
}
}

This filter checks whether the user is logged in. If this is not the case, it outputs a login view and aborts the execution of the controlling plan. The type LoginContext used in the example is fictional and would have to be created by yourself.