【问题标题】:Configure Symfony Route to match database fields配置 Symfony 路由以匹配数据库字段
【发布时间】:2014-08-11 15:53:54
【问题描述】:

我是 Symfony2 的新手,正在通过制作一个 Concert finder 应用程序来学习。

目前我有几个 yaml 路由:

london_hello_bands:
  path:     /hello/{band}
  defaults: { _controller: LondonHelloBundle:Hello:band }

london_hello_multiple:
  path:     /hello/{venue}/{band}
  defaults: { _controller: LondonHelloBundle:Hello:more }

这些映射到我的 HelloController 中的以下操作:

public function bandAction($band)
{
$repository = $this->getDoctrine()
              ->getRepository('LondonHelloBundle:Gig');

$bandinfo = $repository->findByArtist($band);

    return $this->render(
        'LondonHelloBundle:Hello:band.html.twig',
        array('band'=>$bandinfo)
        );
}


public function moreAction($venue, $band)
 {
  $repository = $this->getDoctrine()
              ->getRepository('LondonHelloBundle:Gig');
  $venueinfo = $repository->findBy(
       array('venueName'=>$venue, 'artist'=>$band)
 );

     return $this->render(
      'LondonHelloBundle:Hello:venue.html.twig',
      array('venues'=>$venueinfo)
      );
}

这似乎一切正常,我可以使用 Doctrine 从 /hello/blur 的数据库中提取有关乐队的所有信息(例如),我可以在特定场所显示有关特定乐队的所有信息在 hello/02/blur(例如 - 02 是英国竞技场的名称)。

但是,我也希望能够在 hello/02 之类的 URL 上显示所有乐队在特定场地上演奏,但这与我的第一条路线冲突:

path:     /hello/{band}

有没有一种方法可以将路线与数据库中的特定字段相关联(我在想可能类似于条件https://symfony.com/doc/current/routing.html#matching-expressions)?还是我只需要忍受这个并在 Twig 模板中添加一些逻辑来处理事情?

【问题讨论】:

    标签: php symfony doctrine-orm routing yaml


    【解决方案1】:

    除非您可以使用一些规则来区分乐队和场地名称(例如,乐队名称以小写开头,场地大写),否则您必须在控制器中使用逻辑(而不是模板!)。

    public function bandOrVenueAction($band_or_venue)
    {
        $repository = $this->getDoctrine()
                  ->getRepository('LondonHelloBundle:Gig');
    
        $bandinfo = $repository->findByArtist($band_or_venue);
    
        if(empty($bandinfo) === false) {
    
            return $this->render(
                'LondonHelloBundle:Hello:band.html.twig',
                array('band'=>$bandinfo)
                );
        }
    
        $venueinfo = $repository->findByArtist($band_or_venue);
    
        if(empty($venueinfo) === false) {
    
            return $this->render(
                'LondonHelloBundle:Hello:venue.html.twig',
                array('venueinfo'=>$venueinfo)
                );
        }
    
        // display 404
    }
    

    【讨论】:

    • 好的,谢谢。所以基本上我必须检查数据库,看看是否有一个带与 URL 中的字符串匹配,如果有渲染正确的模板。如果没有检查是否存在与字符串匹配的场所 - 如果存在渲染正确的模板,则处理错误。我想那我只希望没有同名的乐队和场地!
    • 最好添加另一个字段slug,它将保存场地和乐队的网址。你不能相信没有同名的场地,未知的乐队也可以有相同的名字。使用验证器检查 url 是否存在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 2019-11-20
    • 2021-04-27
    相关资源
    最近更新 更多