cakephp 3 prefix routing

5.2k views Asked by At

I'm trying to set up a routing prefix in cakephp 3 so any URLs starting with /json/ get the prefix key set and I can change the layout accordingly in the app controller. Other than that, they should use the usual controller and action. I have added the following to routes.php

$routes->prefix('json', function($routes) {
    $routes->connect(
        '/:controller/:action/*',
        [],
        ['routeClass' => 'InflectedRoute']
    );
});

I want to direct all requests with json as first url segment to controller specified in second url segment. e.g. /json/users/add_account_type/ goes to users controller. However when accessing this URL I get the message:

Error: Create the class UsersController below in file: src/Controller/Json/UsersController.php

whereas I want it to be using

src/Controller/UsersController.php

I think this should be possible but I can't quite see what I'm doing wrong when consulting the book. Have partly based my code on: CakePHP3.x controller name in url when using prefix routing

Thanks a lot in advance

2

There are 2 answers

1
ndm On BEST ANSWER

That's simply how prefix routing now works in 3.x, as explained in the docs, prefixes are being mapped to subnamespaces, and thus to separate controllers in subfolders.

http://book.cakephp.org/3.0/en/development/routing.html#prefix-routing

If you'd wanted to change that behavior (I don't really see why), one way would be to implement a custom ControllerFactory dispatcher filter.

http://book.cakephp.org/3.0/en/development/dispatch-filters.html

On a side note, the RequestHandler component supports layout/template switching out of the box, so maybe you should give that a try.

2
José Lorenzo Rodríguez On

Prefix routing is a way of namespacing parts of your routes to a dedicated controller. It seem that what you want is a scope and not a prefix, for what you describe:

Router::scope('/json', function($routes) {
    $routes->fallbacks('InfledtedRoute')
});