路由設置相關問題
洪老您好,我今天調試了一天路由的配置,有幾個問題還是沒有想明白,請洪老解惑。上代碼:
第一個問題:
#app/config/routing.yml中路由配置 custom: ????resource:?@CustomSiteBundle/Controller/ ????type:?????annotation
#src/Custom/SiteBundle/Controller/DefaultController.php namespace?Custom\SiteBundle\Controller; use?Symfony\Bundle\FrameworkBundle\Controller\Controller; //?these?import?the?"@Route"?and?"@Template"?annotations use?Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use?Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; class?DefaultController?extends?Controller { ????/** ?????*?@Route("/",?name="_demo") ?????*?@Template() ?????*/ ????public?function?indexAction() ????{ ????????return?array(); ????} }
此時可以正常訪問該路由:http://localhost/app.php,但是我新建一個Controller:
#src/Custom/SiteBundle/Controller/CommunalController.php namespace?Site\HomeBundle\Controller; use?Symfony\Bundle\FrameworkBundle\Controller\Controller; //?these?import?the?"@Route"?and?"@Template"?annotations use?Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use?Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; /** ?*?@Route("/communal") ?*/ class?CommunalController?extends?Controller { ????/** ?????*?@Route("/navgate") ?????*?@Template() ?????*/ ???? ????public?function?naygateAction() ????{ ????????return?array(); ????} ???? ????/** ?????*?@Route("/sidebar") ?????*?@Template() ?????*/ ????public?function?sideBarAction() ????{ ????????return?array(); ????} ???? ????/** ?????*?@Route("/footer") ?????*?@Template() ?????*/ ????public?function?footerAction() ????{ ????????return?array(); ????} }
此時訪問/communal下的任何一個方法都報404,http://localhost/app_dev.php/communal
查看官方文檔有:
Including External Routing Resources
All routes are loaded via a single configuration file - usually app/config/routing.yml (see Creating Routes above). However, if you use routing annotations, you'll need to point the router to the controllers with the annotations. This can be done by "importing" directories into the routing configuration:
但不知我這錯在那塊?
還有app/config/routing.yml中custom指的是什么?和@Route("/", name="_demo")中的name是什么關系?
第二個問題:
#修改app/config/routing.yml custom: ????resource:?"@CustomSiteBundle/Resources/config/routing.yml"
#CustomSiteBundle/Resources/config/routing.yml custom: ????resource:?@CustomSiteBundle/Controller/ ????type:?????annotation
修改后訪問http://localhost/app_dev.php,404
這塊又是為什么,我只是換了位置?
請洪老答疑,我覺得路由這塊洪老一筆帶過,尤其是app/config/routing.yml與其他bundle的routing.yml之間關系講的很簡單,難道也是伏筆?
2015-01-27
1.其實你不用試來試去,每個action最終的訪問路徑可以通過命令行工具查看,app/console router:debug
2.我不建議把yml里的key寫成一樣的,也就是說你第一個custom和第二個custom最好換成兩個不重復的名字。判斷routing是否設置成功,配置是否載入成功等等,最好的辦法還是通過上面一條中說到的router:debug去分析,如果這個命令中出現了Path為/的路由,那么你的http://localhost/app_dev.php肯定是可以打開的,如果沒有出現,則必定是404。
2015-01-27
補充一點,在routing.yml中定義路由和在annotation中定義路由是二選其一的兩種定義路由的方式,所以雖然Route里可以定義name,但實際操作上并不會沖突。
2015-01-27
custom就是指這個路由的名字,將來在模板中或者在controller中如果要生成指向某一個路由的鏈接,你就會用到這個名字。