Search code examples
phpphalconphalcon-routing

Routing in Phalcon - parameter before the end of the route


I'm trying to set up routing in Phalcon, following this URL structure:

www.example.com/language/register/

This is my routes.php:

use Phalcon\Mvc\Router;

$router = new Router();

$router->add(
    '/[a-z]{2}/register/',
    array(
        'controller' => 'index',
        'action' => 'register',
        'lang' => 1
    )
);

return $router;

And this is my IndexController:

class IndexController extends ControllerBase
{
    public $lang;

    public function indexAction()
    {

    }

    public function registerAction($lang)
    {
        $lang = $this->dispatcher->getParam('lang');
        echo "Register ($lang)"; //test
    }

}

Therefore, if I was to visit www.example.com/fr/register/ it would take me to the index controller, the register action, with the lang parameter fr.

However, it is not displaying the $lang variable on the page.

I can see in the Phalcon documentation that you cannot use the /:params placeholder anywhere but at the end of the route (URL), but this is a regular expression being named within the router?


Solution

  • You got it right, you just forgot your brackets around [a-z]{2}

    $router->add(
        '/([a-z]{2})/register/', // added brackets here
        array(
            'controller' => 'index',
            'action' => 'register',
            'lang' => 1
        )
    );
    

    Now you can access your lang via

    $lang = $this->dispatcher->getParam('lang');