1
votes

I have a CakePHP 3.5 website. It was necessary to set slugs without any url prefixes like /pages/slug, so I wrote the following rule:

$routes->connect(
    '/:slug',
    ['controller' => 'Pages', 'action' => 'redirectPage']
)
->setMethods(['GET', 'POST'])
->setPass(['slug'])
->setPatterns([
    'slug' => '[a-z0-9\-_]+'
]);

It works nice, but in some cases I want cakePHP to route as default (Controller/Action/Params). For example, I want /admin/login to call 'login' action in 'AdminController'. I have two ideas that doesn't need exact routings, but I can't make any of them to work:

  1. Filtering some strings by pattern: It would be nice if I could filter some strings, that if slug doesn't match pattern, it will simply skip the routing rule.
  2. Create a '/admin/:action' routing rule, but then I cant use :action as an action variable. It causes errors.

    $routes->connect(
        '/admin/:action',
        ['controller' => 'Admin', 'action' => ':action']
    )
    

Any ideas? Thanks

2

2 Answers

4
votes

You can use prefix for admin restricted area. Example:

Router::prefix('admin', function ($routes) {
    $routes->connect('/', ['controller' => 'Users', 'action' => 'login']);
    $routes->fallbacks(DashedRoute::class);
});

$routes->connect('/:slug' , [
    'controller' => 'Pages', 
    'action' => 'display', 
    'plugin' => NULL
], [
    'slug' => '[A-Za-z0-9/-]+', 
    'pass' => ['slug']
]);

Now, for example, path /admin/dashboard/index will execute method in Admin "subnamespace" \App\Controller\Admin\DashboardController::index()

Its nicely described in docs: https://book.cakephp.org/3.0/en/development/routing.html#prefix-routing

1
votes

Try this:

$routes->connect(
    '/admin/:action',
    ['controller' => 'Admin'],
    ['action' => '(login|otherAllowedAction|someOtherAllowedAction)']
);

Also, your slug routes seems to not catch /admin/:action routes, b/c dash is not allowed there: [a-z0-9\-_]+