我知道已经提供了其他一些解决方案,但我想给出更多的解释以及稍微不同的建议。 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使用沿着ParamConverter与Car $car
type hint自动使用slug
财产,并发现该段塞匹配相应的Car
实体。
它实质上是为下,你也可以做,而不是使用帕拉姆转换器的快捷方式:
/**
* @Route("/rent/{slug}")
*/
public function rentAction($slug)
{
$em = $this->getDoctrine()->getManager();
$car = $em->getRepository('AppBundle:Car')->findOneBySlug($slug);
// ...
}
这将让你保持一个友好的URL是有道理的用户,同时也隐藏该ID完全。
谢谢你,完美的解决方案。 – jjpawlica