phpcakephp-3.0cakephp-routing

cakephp 3 prefix routing


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


Solution

  • 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.