PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, December 31, 2021

[FIXED] Cakephp 3 routing with language parameter

 December 31, 2021     cakephp, cakephp-3.0, php, routing     No comments   

Issue

I'm trying to convert cakephp 2.x to 3.x. I was using Router::connect() rules, but I try to convert them to scope version.

Regarding to myold routing rule, in config/routes.php I added this.

  Router::defaultRouteClass('Route');
  Router::scope('/', function ($routes) {

    $routes->connect('/:language/:controller/:action/*', ['language' => 'ar|de|en|fr']);
    $routes->connect('/:language/:controller', ['action' => 'index', 'language' => 'ar|de|en|fr']);
    $routes->connect('/:language', ['controller' => 'Mydefault', 'action' => 'index', 'language' => 'ar|de|en|fr']);

    $routes->redirect('/gohere/*', ['controller' => 'Mycontroller', 'action' => 'myaction'], ['persist' => array('username')]);

    $routes->connect('/', ['controller' => 'Mydefault', 'action' => 'index']);

    $routes->fallbacks('InflectedRoute');
});
  • But this fails in example.com/en/works. I get this error: Error: worksController could not be found. Because my controller file is WorksController.php.

Does controller name part hanged to sentence casein cakephp 3 ? http://book.cakephp.org/3.0/en/intro/conventions.html#controller-conventions

  • Also example.com/foo/bar gives this error: Error: barController could not be found.. But foo is controller and bar is action.

How can I fix this routing problem ?

Edit:
Changing Route::defaultRouteClass('Route') to Route::defaultRouteClass('InflectedRoute') solved problem 1. But problem 2 exists.


Solution

Options, such as route element patterns, must be passed via the third argument of Router::connect(), the $options argument.

This route:

$routes->connect(
    '/:language/:controller',
    ['action' => 'index', 'language' => 'ar|de|en|fr'
]);

will catch your /foo/bar URL, it will match foo for the :language element, and bar for the :controller element. Basically the language key in the URL array will be treated as the default value, and it will always be overwritten by the :language element value.

The correct way of defining the route is:

$routes->connect(
    '/:language/:controller',
    ['action' => 'index'],
    ['language' => 'ar|de|en|fr']
);

The other routes need to be adapted accordingly.

See also Cookbook > Routing > Connecting Routes



Answered By - ndm
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing