Skip to content
Advertisement

CakePHP 3.9 Routing prefixes

I have the following path inside my / Scope:

 $routes->connect('/api/:controller/:action', ['prefix'=>'api'], ['routeClass' => 'DashedRoute']);

And on my src/Controller/UsersController.php i have api_index()

But when i go to the url api/Users/index it says Controller not found, because is asking me to add another UsersController inside a subfolder named Api on Controller folder.

Untill Cakephp 2.x using this behavior worked fine for me, how can i achieve the same behavior on CakePHP 3.x like it was on Cakephp 2.x ?

Thank you very much !

Advertisement

Answer

From cakephp book

Prefix Routing static CakeRoutingRouter::prefix($name, $callback) Many applications require an administration section where privileged users can make changes. This is often done through a special URL such as /admin/users/edit/5. In CakePHP, prefix routing can be enabled by using the prefix scope method:

use CakeRoutingRouteDashedRoute;

Router::prefix('admin', function (RouteBuilder $routes) {
    // All routes here will be prefixed with `/admin`
    // And have the prefix => admin route element added.
    $routes->fallbacks(DashedRoute::class);
})

;

Prefixes are mapped to sub-namespaces in your application’s Controller namespace. By having prefixes as separate controllers you can create smaller and simpler controllers. Behavior that is common to the prefixed and non-prefixed controllers can be encapsulated using inheritance, Components, or traits. Using our users example, accessing the URL /admin/users/edit/5 would call the edit() method of our src/Controller/Admin/UsersController.php passing 5 as the first parameter. The view file used would be src/Template/Admin/Users/edit.ctp

You can map the URL /admin to your index() action of pages controller using following route:

Router::prefix('admin', function (RouteBuilder $routes) {
    // Because you are in the admin scope,
    // you do not need to include the /admin prefix
    // or the admin route element.
    $routes->connect('/', ['controller' => 'Pages', 'action' => 'index']);
});

https://book.cakephp.org/3/en/development/routing.html#prefix-routing

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement