[英]How to singularize route path part using FOSRestBundle
I have this controller (a snippet here)我有这个控制器(这里有一个片段)
/**
* Class UserController
* @package Belka\AuthBundle\Controller
*/
class UserController extends FOSRestController implements ClassResourceInterface
{
/**
* @View()
*
* @Route(requirements={"user"="\w+"})
* @ParamConverter("user", converter="fos_rest.request_body")
*/
public function postGlobaltokenAction(User $user)
{
...
}
that automatically generates the route:自动生成路由:
post_user_globaltoken POST ANY ANY /api/users/{user}/globaltokens.{_format}
which is OK, except for the fact I would like "globaltoken" singularized.没关系,除了我希望“globaltoken”单数化的事实。 Is that possible?
那可能吗? I cannot find any annotation to tweak this.
我找不到任何注释来调整这个。 Should I hardcode the route in my
route.yml
?我应该在
route.yml
对路线进行硬编码吗?
I've found two ways:我找到了两种方法:
Using a personal Inflector
使用个人
Inflector
as Symfony's documentation suggests, you can register a personal Inflector
which returns "globaltoken" always as singular, whereas all the other resources will be pluralized:正如Symfony 的文档所暗示的那样,您可以注册一个个人
Inflector
,它始终以单数形式返回“globaltoken”,而所有其他资源将变为复数形式:
use Doctrine\Common\Util\Inflector;
use FOS\RestBundle\Util\Inflector\DoctrineInflector;
use FOS\RestBundle\Util\Inflector\InflectorInterface;
/**
* Inflector class
*
*/
class NoopInflector extends DoctrineInflector implements InflectorInterface
{
public function pluralize($word)
{
if($word == "globaltoken")
return $word;
return parent::pluralize($word);
}
}
services.yml:服务.yml:
services:
belka.auth_bundle.util.inflector:
class: Belka\AuthBundle\Util\NoopInflector
but I found this way a bit dirty, as I could need the plural form in the future.但我发现这种方式有点脏,因为我将来可能需要复数形式。
Overriding the FOSRestBundle
auto-generated routes覆盖
FOSRestBundle
自动生成的路由
It's that simple!就是这么简单! Just add the
@Route
annotation on the right methos and you're done!只需在正确的方法上添加
@Route
注释,就大功告成了!
/**
* @View()
*
* @Route("/users/{user}/globaltoken", defaults={"_format" = "json"}, requirements={"user"="\w+"})
*
* @ParamConverter("user", converter="fos_rest.request_body")
*/
public function postAction(User $user)
{
}
Now if I call php app/console debug:route
I get what I want:现在,如果我调用
php app/console debug:route
我会得到我想要的:
post_user_globaltoken POST ANY ANY /api/users/{user}/globaltoken.{_format}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.