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

translated routes

I had tried to ask this question in a previous discussion of the forum (here) but nobody answered, maybe because it was already signed as 'solved', so I will ask it here.

I need to have the possibility to translate the url of my website, without duplicating controllers and actions; so, for example, if I write 'Baseurl\it\contatti' I'll go to tthe controller 'contacts' and I will have the italian language, if I write 'Baseurl\en\contacts' I'll go in the same controller, but with english language.

The problem is in the routing part:

in the solution presented in the linked discussion I don't understand how to use only one controller, without duplicating each one for every language.

So, does anyone have some good advice? Thanks.

edited Feb '16

Something like this should work.

i haven't tested it but it should work.

router file in cofigs

$router = new Phalcon\Mvc\Router();
$router->add('/{language}/:controller/:action/:params', array(
    'controller' => 2,
    'action' => 3,
    'params' => 4
));

This is the controller base i like to run things through bases for any conversion i need to do to glboal stuffs.

class ControllerBase extends Controller
{
    public function beforeExecuteRoute(Dispatcher $dispatcher){
        // grabbing controller from dispatcher
        $controllerName = $dispatcher->getControllerName();
        // get my language from router variable set in router file
        $language = $this->dispatcher->getParam('language');

        $dispatcher->forward(array(
            // set controller to the based on language
            'controller' => ($language == 'en') ? $controllerName : $this->map_control($controllerName),
            // set the action from dispatcher, index, view, edit, delete. you could do a map on this as well. 
            'action' => $dispatcher->getActionName()
        ));
    }

    private function map_control($name){
        // map of controler names from it to english. obviously you coudl do this in reverse order if you prefer to write in italian. i am writing form an english perspective
        $func_map = array(
            'contatti' => 'contacts'
        );
        return $func_map[$name];
    }
}

Here is your contact controller.

class Contact extends ControllerBase
{
    public function index()
    {
        $this->view->helloworld = 'Hello World';
    }
}

Thanks for the answer! Anyway it made me think about two "problems"...

First, the fact that I will have many languages, and many controllers/actions that I'll add 'on the way', so the map maybe it's not the best or most portable solution, but if there is not another one I guess I'll try that.

Second, and more important, I need to make only one request for accessing a page. Doing the dispatcher->forward don't I make a second one?