CakePHP 4 - Using Custom Prefixes for Routers & Templates (Other Than Admin)

CakePHP 4 - Using Alternative Prefixes Other Than Admin

Sometimes when creating your CakePHP application, you might want to separate functionality of controllers and templates into folders.  This can be helpful, for example, when you want to organize specific actions into different controllers.

In this example, we want to allow certain users to manage their shops (AdminShop prefix), separately from the public (No prefix), or a regular Administrator (Admin prefix).

Current Folder Structurre:

/src/Controller/UsersShopsController,php
/src/templates/UserShop/index.php

AND
/src/Controller/Admin/UsersShopsController.php
/src/templates/Admin/UserShops/index.php

Current Routing (/config/routes.php):

$routes->prefix('admin', function($routes) {
    $routes->connect('/', ['controller' => 'Users', 'action' => 'login']);
    $routes->fallbacks('InflectedRoute');
});

New structure with current / existing, but using a separate prefix:

/src/Controller/UsersShopsController,php
/src/templates/UserShop//index.php

AND
/src/Controller/Admin/UsersShopsController.php
/src/templates/Admin/UserShops/index.php

AND
/src/Controller/AdminShop/UsersShopsController.php
/src/templates/AdminShop/UserShops/index.php

Revised Routing to Accommodate AdminShop/{controller]/{action} (/config/routes.php):

$routes->prefix('admin', function($routes) {
    $routes->connect('/', ['controller' => 'Users', 'action' => 'login']);
    $routes->fallbacks('InflectedRoute');
});
$routes->prefix('adminshop', function($routes) {
    $routes->connect('/');
    $routes->fallbacks('InflectedRoute');
});

 

Final Note:Modify your controller:

When placing controllers in subfolders, you'll need to modify the namespace and specify the AppController to use.  In the above example, we would edit the /src/Controller/AdminShop/UserShopsController.php, adding the below lines in the top of your controller:

namespace App\Controller\UsersShop;

use App\Controller\AppController;

Share this Post