We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Request Filters

Is there in Phalcon official way to handle request filters.

Currently after initializing application I execute numer of filter objects like:

  • HttpsFilters (make sure request use SSL connection)
  • LanguageFilter (set language base on request in session)
  • RememberMeFilter (login user base on remember me cookie)
  • SecurityFilter (check if user has access to routed resource - ACL)

Hi Tomasz, As I know there are no official way ;)

I did it in this way, it is only simple example checking if session admin is set

index.php

$di->set("dispatcher", function() {
        $eventManager = new \Phalcon\Events\Manager();
        $eventManager->attach("dispatch:beforeException", function($event, $dispatcher, $exception) {
                if($exception instanceof \Phalcon\Mvc\Dispatcher\Exception) {
                    $dispatcher->forward(array(
                            "controller" => "index",
                            "action" => "index"
                        ));
                    return false;
                }
            });

        $dispatcher = new \Phalcon\Mvc\Dispatcher();

        $dispatcher->setEventsManager($eventManager);

        return $dispatcher;
    });

Base Controller

class ControllerBase extends Phalcon\Mvc\Controller
{
    public function onConstruct() //this constructor/initializator is executed even if action isn't exist, you could handle your filter here
    {
        if($this->session->get("admin")!==1)
        {
            $this->request->redirect("login/index");
        }
    }

    public function initialize()
    {

    }
}

IndexController

class IndexController extends ControllerBase  //i use it for every controller
{
    public function indexAction()
    {

    }
}

LoginController

class LoginController extends \Phalcon\Mvc\Controller //i use it when no admin
{
    public function indexAction()
    {

    }
}


98.9k

You can use beforeMatch in the case to implement a similar behavior:

<?php

class AjaxFilter
{
    public function check()
    {
        return $_SERVER['X_REQUESTED_WITH'] == 'xmlhttprequest';
    }
}
<?php

$router->add('/get/info/{id}', array(
    'controller' => 'products',
    'action' => 'info'
))->beforeMatch(array(new AjaxFilter(), 'check'));

https://docs.phalcon.io/en/latest/reference/routing.html#match-callbacks

Just a note that you can do your HTTPS redirection in Apache or .htaccess, without needing to instantiate any PHP code.