This question concerns routing (config/routes.php
) in CakePHP 3.7.3
I have an application which uses 3 Controllers. Two of these are within an 'Admin' namespace:
Controller/Admin/ArticlesController.php
Controller/Admin/UsersController.php
Controller/ArticlesController.php
I'm trying to achieve the following things:
Make a "shortcut" URL
https://example.com/admin
that servesAdmin/UsersController::login()
- i.e.https://example.com/admin/users/login
The function that shows pages on the frontend of my website is
ArticlesController::view()
. If I have a URL slug "foo" my page serves the content from the URLhttps://example.com/articles/view/foo
. However I want to make this justhttps://example.com/foo
.
In my config/routes.php
I have configured Admin routing with this:
Router::scope('/', function (RouteBuilder $routes) {
Router::prefix('admin', function ($routes) {
// All routes here will be prefixed with `/admin`
// And have the prefix => admin route element added.
$routes->fallbacks(DashedRoute::class);
});
$routes->fallbacks(DashedRoute::class);
});
This works - I can login at https://example.com/admin/users/login
.
To solve (1) I attempted to add the following:
Router::connect('/admin', ['controller' => 'Users', 'action' => 'login']);
// The line above is immediately outside the existing code shown previously:
Router::scope('/' ...
But this gives me an error:
Error: AdminController could not be found.
Error: Create the class AdminController below in file:
src/Controller/AdminController.php
The Controller it's being asked to use is Users
so I don't understand why it's asking for an AdminController
?
To solve (2) I attempted:
$routes->connect('/*', ['controller' => 'Articles', 'action' => 'view]);
However when attempting to access https://example.com/foo
it is giving the following error:
Error: FooController could not be found.
Clearly this isn't what I'm trying to do - I'm expecting it to use the Articles
Controller and view
action I've specified in the array.
In my two Admin Controllers (Controller/Admin/ArticlesController.php
and Controller/Admin/UsersController.php
) I have declared:
namespace App\Controller\Admin;
outside the class name, e.g. class ArticlesController extends AppController
For the non-Admin ArticlesController
(Controller/ArticlesController.php
) I have declared:
namespace App\Controller;
followed by the class name class ArticlesController extends AppController
This seems overly complex. Can anyone help?