Symfony2: use object to set route parameters

前端 未结 2 1605

I have a route with 2 parameters:

BBBundle_blog_show:
    pattern:  /{id}/{slug}
    defaults: { _controller: BloggerBlogBundle:Blog:show }
    requirements:         


        
2条回答
  •  一向
    一向 (楼主)
    2020-12-09 21:35

    A while ago, I decided I was annoyed by being unable to pass objects as route parameters. I had to concern myself with knowledge of routes and the exact parameter values within templates and other things generating those routes.

    I've build this bundle for symfony, which allows you to use and extend this ability (Symfony 2.7 and higher). Please take a look: https://github.com/iltar/http-bundle. It's also available on Packagist as iltar/http-bundle.

    The best thing about this bundle is that you don't need to use another router object or generator. It's just turning on the bundle, adjusting the config to your needs if the defaults don't work out for your preferences and you're good to go. The readme should explain everything you need to know but here's a snippet:

    Old style:

    /**
     * @Route("/profile/{user}/", name="app.view-profile")
     */
    public function viewProfileAction(AppUser $user);
    
    // php
    $router->generate('app.view-profile', ['user' => $user->getId()]);
    
    // twig
    {{ path('app.view-profile', { 'user': user.id }) }}
    {{ path('app.view-profile', { 'user': user.getid }) }}
    {{ path('app.view-profile', { 'user': user.getId() }) }}
    {{ path('app.view-profile', { 'user': user[id] }) }}
    

    New style:

    // php
    $router->generate('app.view-profile', ['user' => $user]);
    
    // twig
    {{ path('app.view-profile', { 'user' : user }) }}
    

提交回复
热议问题