Sunday, February 13, 2022

[FIXED] How to use Router Connect method correctly in CakePHP 2 and 3?

Issue

I have a controller MyUsersController with an action login. I have mapped this with:

$routes->connect('/member/login', [ 'controller' => 'MyUsers', 'action' => 'login', 'plugin'=>false, 'prefix'=>FALSE]);

Now I can access this action "login" using these two urls which is not good for SEO.

http://localhost/cakephpapp/member/login

http://localhost/cakephpapp/my-users/login

So, how can I disable the second URL?

I have tried this code which is working fine but I don't know whether this is correct method or not.

$routes->redirect('/my-users/login', '/member/login');

Solution

There is a line in the default routes file that provides the fallbacks so that you can access pages using controller/action. This is really to help you quickly scaffold an app. In CakePHP 3 this is:-

$routes->fallbacks('InflectedRoute');

As commented in the file you can/should remove this line once you have set up the routes for your application. If you remove this it will also prevent your error logs from filling with errors like 'Missing Controller' which can be an issue on a production site, particularly if it is replacing an existing one.

In CakePHP 2 the equivalent line is this:-

require CAKE . 'Config' . DS . 'routes.php';

Removing these lines does mean that you will have to define all routes for your application, but that is probably a better practice than relying on automagic routes of Cake (or any framework). There's a good article on this by Phil Sturgeon: Beware the Route to Evil.



Answered By - drmonkeyninja

No comments:

Post a Comment

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