2015-07-12 102 views
6

我試圖將cakephp 2.x轉換爲3.x.我正在使用Router::connect()規則,但我嘗試將它們轉換爲範圍版本。CakePHP 3路由與語言參數

關於myold路由規則,在config/routes.php我加了這個。

Router::defaultRouteClass('Route'); 
    Router::scope('/', function ($routes) { 

    $routes->connect('/:language/:controller/:action/*', ['language' => 'ar|de|en|fr']); 
    $routes->connect('/:language/:controller', ['action' => 'index', 'language' => 'ar|de|en|fr']); 
    $routes->connect('/:language', ['controller' => 'Mydefault', 'action' => 'index', 'language' => 'ar|de|en|fr']); 

    $routes->redirect('/gohere/*', ['controller' => 'Mycontroller', 'action' => 'myaction'], ['persist' => array('username')]); 

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

    $routes->fallbacks('InflectedRoute'); 
}); 
  • 但這種失敗在example.com/en/works。我得到這個錯誤:Error: worksController could not be found.因爲我的控制器文件是WorksController.php

控制器名稱部分是否被判處casein cakephp 3? http://book.cakephp.org/3.0/en/intro/conventions.html#controller-conventions

  • example.com/foo/bar給出了這樣的錯誤:Error: barController could not be found.。但foo是控制器,bar是行動。

我該如何解決這個路由問題?

編輯:
更改Route::defaultRouteClass('Route')Route::defaultRouteClass('InflectedRoute')解決了問題1.但存在問題2。

+0

必須有一條線'路線:: defaultRouteClass( 'Route')'在你的routes.php的頂部。將其更改爲'Route :: defaultRouteClass('InflectedRoute')'。 – ADmad

+0

此固定錯誤1.但存在錯誤2。當我輸入'example.com/foo/bar'時,cakephp會查找barController。 – trante

回答

5

必須通過參數Router::connect()的第三個參數$options參數傳遞選項,例如路徑元素模式。

這條路線

$routes->connect('/:language/:controller', ['action' => 'index', 'language' => 'ar|de|en|fr']); 

會抓住你的/foo/bar URL,它將匹配foo:language元素,bar:controller元素。

定義路線的正確的方法是

$routes->connect(
    '/:language/:controller', 
    ['action' => 'index'], 
    ['language' => 'ar|de|en|fr'] 
); 

,其餘的路由需要被相應的調整。

參見Cookbook > Routing > Connecting Routes

1

最好的辦法是使用路由作用域取自

<?php 
$builder = function ($routes) { 
    $routes->connect('/:action/*'); 
}; 
$scopes = function ($routes) use ($builder) { 
    $routes->scope('/questions', ['controller' => 'Questions'], $builder); 
    $routes->scope('/answers', ['controller' => 'Answers'], $builder); 
}; 

$languages = ['en', 'es', 'pt']; 
foreach ($languages as $lang) { 
    Router::scope("/$lang", ['lang' => $lang], $scopes); 
} 

Router::addUrlFilter(function ($params, $request) { 
    if ($request->param('lang')) { 
     $params['lang'] = $request->param('lang'); 
    } 
    return $params; 
}); 

代碼:

https://github.com/steinkel/cakefest2015/blob/c3403729d7b97015a409c36cf85be9b0cc5c76ef/cakefest/config/routes.php