cakePHP3前缀路由和控制器/子控制器

时间:2017-11-20 13:50:10

标签: cakephp routing cakephp-3.0

我(更确切地说是“想要”)以下结构,我尝试构建路线:

src/Controller/OrdersController.php
src/Controller/Orders/PositionsController.php

所以路线是:

/orders > OrdersController
/orders/details/1 > OrdersController:details
/orders/positions/details/1 > PositionsController:details

解决方案是前缀路由,到目前为止,这么好。但它只适用于前缀路由之前的固定路由。

这样可行:

Router::scope('/', function (RouteBuilder $routes)
{
    $routes->connect('/orders/details/*', [
        'controller' => 'Orders',
        'action' => 'details'
    ]);
    $routes->prefix('orders', function (RouteBuilder $routes)
    {
        $routes->fallbacks(DashedRoute::class);
    });    
    $routes->fallbacks(DashedRoute::class);
});

但我希望它更灵活,不要定义每条路线。我可以使用“:action”标志来定义路线。

最好的情况是有多个级别,如:

src/Controller/OrdersController.php
src/Controller/Orders/PositionsController.php
src/Controller/Orders/Positions/CommentsController.php

有可能吗? 这将是更“结构”而不是OrdersController,OrdersPositionsController和OrdersPositionsCommentsController,......

1 个答案:

答案 0 :(得分:0)

我可以自己解决:

Router::scope('/', function (RouteBuilder $routes)
{
    $routes->prefix('orders', [], function (RouteBuilder $routes)
    {
        // -- order positions
        $routes->connect('/positions', [
            'controller' => 'Positions',
            'action' => 'index'
        ]);
        $routes->connect('/positions/:action/*', [
            'controller' => 'Positions'
        ]);

        $routes->prefix('positions', [], function (RouteBuilder $routes)
        {
            $routes->connect('/comments', [
                'controller' => 'Comments',
                'action' => 'index'
            ]);
        });

    });

    $routes->fallbacks(DashedRoute::class);

});