为什么这个Symfony2路由不起作用?

时间:2012-07-28 13:14:58

标签: php symfony

我在Symfony2中遇到路由问题。

实际上我下载了最新版本并在我的服务器上运行它。该演示工作正常。

现在我要做以下事情: 我想创建一个TestController,这个控制器应该有:

  • 索引视图
  • 像hello world这样的视图
  • 我可以传递2个参数的视图

所以我开始在名为src\Acme\DemoBundle\Controller的{​​{1}}文件夹中创建一个新控制器。这是代码:

TestController

然后我在名为<?php namespace Acme\DemoBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\RedirectResponse; use Acme\DemoBundle\Form\ContactType; // these import the "@Route" and "@Template" annotations use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; class TestController extends Controller { public function indexAction() { return array(); } public function hello2Action($name1, $name2) { return array(); } public function helloAction() { return array(); } } src\Acme\DemoBundle\Resources\views\Testhello.html.twig

的新文件夹index.html.twig中创建了3个观看次数

他们都有这样的内容

hello2.html.twig

最后我编辑了{% extends "AcmeDemoBundle::layout.html.twig" %} {% block title "Symfony - Demos" %} {% block content_header '' %} {% block content %} foo!!! {% endblock %} 并添加了这样的内容:

routing.dev.yml

当我想运行测试控制器时,我得到:

  

找不到“GET / test /”

的路线

有什么问题? 是否可以为两个控制器功能提供一个视图? (比如hello()和hello($ foo))?

3 个答案:

答案 0 :(得分:3)

你也可以这样做:

  1. 在routing_dev.yml中,请确保您拥有:

     _main:
         resource: routing.yml
    
  2. 在routing.yml中,添加如下内容:

       AcmeDemoBundle:
          resource: "@AcmeDemoBundle/Resources/config/routing.yml"
          prefix:   /test
    

    您可以选择所需的前缀来访问该特定包。

  3. 在Acme / DemoBundle / Resources / config / routing.yml中,您现在可以添加路由模式。

      name1:
          pattern: /
          defaults: { _controller: AcmeDemoBundle:Test:index }
    
      name2:
          pattern: /hello
          defaults: { _controller: AcmeDemoBundle:Test:hello }
    
      name3:
          pattern: /hello2/{name1}/{name2}
          defaults: { _controller: AcmeDemoBundle:Test:hello2 }
    
  4. 您现在可以访问,路由 / test / test / hello / test / hello2 / firstname / lastname'。这只是管理symfony 2中路由的一种方法。这可能会有所帮助:http://symfony.com/doc/current/book/routing.html

答案 1 :(得分:1)

两件事:

  • 您已为“/ test”定义了路由,但没有为“/ test /”定义路由,这就是您收到第一条错误消息的原因(找不到“GET / test /”的路由)。在任何情况下,最好将路由定义为注释,如另一个答案所示。

  • 为了让控制器使用您正在使用的结构(返回和变量数组,在本例中为空数组),您需要使用“@Template”注释标记它们,如下所示:

  

/ *

* @Route("/hello/{name}", name="_demo_hello")
* @Template()
*/    
public function helloAction($name)

这使Symfony自动查找相应的模板文件。如果你不这样做,你需要返回一个Response对象,指出应该呈现的模板,如下所示:

return $this->render('AcmeDemoBundle:Test:index.html.twig');

答案 2 :(得分:0)

在您的路由中,您定义了前缀,但实际上并未定义路由。由于您正在使用注释 - 必须通过Controller中的注释来定义路径。

请参阅此great manual;)

您的routing_dev.yml应如下所示:

_name1:
    resource: "@AcmeDemoBundle/Controller/TestController.php"
    type:     annotation

在你的控制器中你应该为每个动作定义@Route:

/**
 * @Route("/hello")
 */
public function helloAction()
{
    return array();
}

在此之后,您将能够通过路线/hello等访问您的操作。

干杯;)

相关问题