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

Group routes in Micro(): Approach

I want to group routes:

$userGroup = new \Phalcon\Mvc\Router\Group('user');

$app->map('/user/login', function () {
   // code...
})->setName('user.login')->setGroup($userGroup);

And I retrieve the information:

// get route name
$routeName = $app->router->getMatchedRoute()->getName();
// get group name <- work , but I do not like getPaths()
$groupName = $app->router->getMatchedRoute()->getGroup()->getPaths();
//but getRoutes() NOT WORK.
$groupName = $app->router->getMatchedRoute()->getGroup()->getRoutes();

I implement something that helps to group routes, and so to separate code into different files and folders.

any ideas?



40.1k
Accepted
answer

My solution:

<?php

namespace Druphal\Core;

class Route extends \Phalcon\Mvc\Router\Route
{
    protected $moduleName;

    public function getModuleName()
    {
        return $this->moduleName;
    }

    public function setModuleName($name)
    {
        $this->moduleName = $name;
        return $this;
    }

}
<?php

namespace Druphal\Core;

use Druphal\User\Auth\Exception;

class Router extends \Phalcon\Mvc\Router
{
    public function add($pattern, $paths = null, $httpMethods = null, $position = Router::POSITION_LAST)
    {
        $route = new Route($pattern, $paths, $httpMethods);

        switch ($position) {
            case parent::POSITION_LAST:
                $this->_routes[] = $route;
                break;
            case parent::POSITION_FIRST:
                $this->_routes = array_merge([$route], $this->_routes);
                break;
            default:
                throw new Exception("Invalid route position");
        }

        return $route;
    }
}

in services.php

$di->setShared('router', function () {
    return new Druphal\Core\Router();
});

And I use:

$app->map('/user/login', function () {
     // code...
})->setName('user.login')->setModuleName('user');

in before function:

$app->before(function () use ($app) {
    $routeName = $app->router->getMatchedRoute()->getName();
    $moduleName = $app->router->getMatchedRoute()->getModuleName();
    // logic here....
    return true;
});

work fine.