删除一些默认创建的后备路由

时间:2019-07-03 06:29:29

标签: routes cakephp-3.x

在CakePHP 3中,默认行为是DashedRoutes,我对此感到满意。但是,在某些情况下,我想用自己的自定义路由替换路由并删除默认创建的路由。我的路线文件如下所示:

<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
use Cake\Routing\Route\DashedRoute;

Router::defaultRouteClass(DashedRoute::class);

Router::scope('/', function (RouteBuilder $routes) {
    $routes->registerMiddleware('csrf', new CsrfProtectionMiddleware([
        'httpOnly' => true
    ]));

    $routes->applyMiddleware('csrf');

    $routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);

    $routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);

    $routes->connect('/register', ['controller' => 'Users', 'action' => 'register']);
    $routes->connect('/login', ['controller' => 'Users', 'action' => 'login']);
    $routes->connect('/logout', ['controller' => 'Users', 'action' => 'logout']);

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

在这种情况下,我希望以下路由不起作用,并且基本上返回404错误:

/users/login
/users/logout
/users/register

我将如何“断开”这些路线?

1 个答案:

答案 0 :(得分:0)

您可能只需要为/users/*设置另一条路由即可使用404重定向功能,就可以将其基本上添加到该路由中:

$routes->connect(
    '/users/*',
    ['controller' => 'Users', 'action' => 'serve404']
);

然后将其发送到UsersController(或者如果您希望AppController供以后重用):

public function serve404(){
    throw NotFoundException();
}