简体   繁体   中英

Symfony 2 or 3 ParamConverter

I don't understand one question. When use controllers with routes example

/**
 * @Route("/news/comment-delete/{comment_id}",
 *      name = "blog_deleteComment"
 * )
 *  @ParamConverter("comment", class="pfrechowiczBlogBundle:Comment", options={"id" = "comment_id"})
 */

and in HTML giving argument to controller

<a href="{{ path('blog_deleteComment', {'comment_id' : comment.id}) }}" class="blog_deleteComment" >Usuń</a>

it's work OK, but when i change "_" to "-" it's not working and i dont know why couldnt find answer. This problem is only when have to use ParamConverter with urls with "-" without ParamConverter's Route's which use "-" are OK.

This one example it's not working:

    /**
     * @Route("/news/comment-delete/{comment-id}",
     *      name = "blog_deleteComment"
     * )
     *  @ParamConverter("comment", class="pfrechowiczBlogBundle:Comment", options={"id" = "comment-id"})
     */

and HTML code:

<a href="{{ path('blog_deleteComment', {'comment-id' : comment.id}) }}" class="blog_deleteComment" >Usuń</a>

Could someone explain this?

There is no such thing as a variable named $var-iable because it equates to $var - iable . You don't want the result of subtracting a constant that doesn't exist from $var though... PHP does not allow variables to have hyphens in their name because it would be too confusing differentiating between subtraction and an actual variable.

You can create a variable named $var_iable though. What's between the {} enclosure in your route is translated into a $variable based on your name and passed into your controller method. Symfony has addressed the fact that hyphens are not allowed in variables in PHP.

tldr: Use camel case or an underscore.

PHP语法不允许在变量名称中使用连字符。

I have always tried to follow the rule that a route should always try to follow something like

<controller>/action/{id}

where the id is optional. While I constantly read that dashes are more favorable to use in URLs instead of underscores, I try to avoid both. Your route would better be something like this:

* @Route("/news/comment/delete/{id}",

OR even better

* @Route("/comment/delete/{id}",

If "news" doesn't NEED to be in the url pattern, leave it out. Otherwise you could look at it as in the news section, in the comment controller there is an action named "delete" that you are passing in an "id". You had "comment-id" but it's obvious that you are passing in a comment id. If you have time look up some documentation on RESTful URLs.

But to answer your question about coding in php, I'd recommend never using dashes in the PHP code or in MySQL databases as field or table names. When coding it is much better to use underscores.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM