2016-02-09 41 views
1

我正在我的大学编程课上为Symfony建设简单的汽车租赁应用程序。Symfony - 点击了哪个链接

的问题,我不知道如何解决是休耕:

形式的数据库查询,我得到可用的汽车名单,我很容易地显示他们用树枝模板。

我想要一个按钮,每个列出的车链接到/出租网站,其中用户提供所有所需的信息。

我知道我可以使用类似的东西:

<a href="{{ path('rent', {'id': car.id}) }}"> 

但是是有控制器负责这条路线知道被点击哪个链接任何其他方式?毕竟我需要知道哪个汽车用户想要租用,而且我不想以url/rent/{id}结尾。

回答

0

我知道已经提供了其他一些解决方案,但我想给出更多的解释以及稍微不同的建议。 Pipe的回应是正确的,并且有效,但是为了您的目的,我不会仅仅为每辆车生成一个随机标记,我会将每个与搜索引擎优化相关的车都绑定一个slug

例如,在你的车表,你会:

+-------+--------------+ 
| id | slug  | 
+-------+--------------+ 
| 1 | ford-150  | 
| 2 | cadillac-cts | 
+-------+--------------+ 

那么你的实体将有相应的变量和教义的注解会看起来像:

namespace AppBundle\Entity; 

use Doctrine\ORM\Mapping as ORM; 

class Car 
{ 
    /** 
    * @var int 
    * 
    * @ORM\Id 
    * @ORM\Column(name="id", type="integer") 
    * @ORM\GeneratedValue(strategy="IDENTITY") 
    */ 
    private $id; 

    /** 
    * @var string 
    * 
    * @ORM\Column(name="slug", type="string", length=50, nullable=false) 
    */ 
    private $slug; 
} 

现在联系你生成在你的树枝看起来像这样:

<a href="{{ path('rent', {'slug': car.slug}) }}"> 

然后你的控制奥勒/路由可以定义为这样的:

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 
use Symfony\Bundle\FrameworkBundle\Controller\Controller; 

class RentController extends Controller 
{ 
    /** 
    * @Route("/rent/{slug}", name="rent") 
    */ 
    public function rentAction(Car $car) 
    { 
     // logic here 
    } 
} 

这里的Symfony使用沿着ParamConverterCar $cartype hint自动使用slug财产,并发现该段塞匹配相应的Car实体。

它实质上是为下,你也可以做,而不是使用帕拉姆转换器的快捷方式:

/** 
* @Route("/rent/{slug}") 
*/ 
public function rentAction($slug) 
{ 
    $em = $this->getDoctrine()->getManager(); 
    $car = $em->getRepository('AppBundle:Car')->findOneBySlug($slug); 

    // ... 
} 

这将让你保持一个友好的URL是有道理的用户,同时也隐藏该ID完全。

+0

谢谢你,完美的解决方案。 – jjpawlica

0

如果你不想显示的URL的car.id,为每个汽车随机“令牌”,并作出这样的网址:

<a href="{{ path('rent', {'id': car.token}) }}"> 

这将是/rent/abcd5437fbadce88