PHP code example of anton-am / phalcon-middleware

1. Go to this page and download the library: Download anton-am/phalcon-middleware library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

anton-am / phalcon-middleware example snippets


use AntonAm\Phalcon\Middleware\Event;
use Phalcon\Events\Manager;
use Phalcon\Mvc\Dispatcher;

// ...

$di->set(
    "dispatcher",
    function () use ($di) {
            $eventsManager = new Manager();
            
            //Attach a listener
            $eventsManager->attach(
                'dispatch:beforeExecuteRoute',
                new Event()
            );

            $dispatcher = new Dispatcher();
            $dispatcher->setEventsManager($eventsManager);
            return $dispatcher;
    },
    true
);

namespace Modules\Frontend\Middlewares;

use Phalcon\Mvc\User\Plugin;
use AntonAm\Phalcon\Middleware\MiddlewareInterface;

/**
 * Class CSRF
 *
 * @package Modules\Frontend\Middlewares
 */
class CSRF extends Plugin implements MiddlewareInterface
{
    /**
     * @param array $params
     * @return bool
     */
    public function handle(array $params = []): bool
    {
        if (!$this->security->checkToken()) {
            $this->flashSession->error('Wrong CSRF');
            $this->response->redirect($this->request->getHTTPReferer(), true)->send();
            return false;
        }

        return true;
    }

class IndexController extends \Phalcon\Mvc\Controller
{
    /**
     * @Middleware("Modules\Frontend\Middlewares\MustBeLoggedIn")
     * @Middleware("Modules\Frontend\Middlewares\HasProject")
     * @Middleware("Modules\Frontend\Middlewares\MustBeInProjectAs", "Creator")
     * @Middleware("Modules\Frontend\Middlewares\CSRF")
     */
    public function indexAction()
    {
        // ...
    }
}