AKKAweb
AKKAweb

Reputation: 3807

CakePHP 3 - Controller not found when setup thru routes.php

Trying to play around with a test API. Based on the following routes setup, if I request /v1/tests/index.json I will get a JSON Object Response as expected, but if I request /v1/test/index.json I will get an error that TestController is missing. I have checked docs and I can't seem to figure out what is wrong. I expected the $routes->connect('/test', [...]); to work, but it is not. Any help in shining some light into this is appreciated.

<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;

Router::defaultRouteClass('DashedRoute');
Router::extensions(['json', 'xml']);

Router::scope('/', function (RouteBuilder $routes) {
    $routes->prefix('v1', function (RouteBuilder $routes) {
        $routes->connect('/test', ['controller' => 'Tests', 'action' => 'index']);
        $routes->fallbacks('InflectedRoute');
    });

    $routes->fallbacks('DashedRoute');

});

Plugin::routes();

Upvotes: 0

Views: 610

Answers (2)

SamHecquet
SamHecquet

Reputation: 1836

Did you try to specify the action in the route connect?

$routes->connect('/test/index', ['controller' => 'Tests', 'action' => 'index']);

Upvotes: 1

ndm
ndm

Reputation: 60463

There is no explicit route set up matching /v1/test/index.json. Your:

$routes->connect('/test', ['controller' => 'Tests', 'action' => 'index']);

route will match /v1/test or /v1/test.json|xml, and that's all.

/v1/test/index.json will be catched by the fallback routes, and hence try to connect to the controller matching test, ie TestController.

Check out Cookbook > Routing > Connecting Routes more closely, you're doing what is shown in the /government example.

Upvotes: 2

Related Questions