简体   繁体   English

生成的Symfony2控制器和FOSRestBundle控制器之间有什么区别?

[英]What is the difference between generated Symfony2 controller and FOSRestBundle controller?

I am confused about this question and I would be greatful if someone could give me an explanation with concrete examples. 我对这个问题感到困惑,如果有人可以给我一个具体例子的解释,我将非常感激。 I generated a CRUD controller with Symfony and also implemented FOSRestBundle Controller for REST. 我使用Symfony生成了CRUD控制器,还为REST实现了FOSRestBundle控制器。 They both return the same data and I am wondering, what is the difference and what can one do that the other cannot? 它们都返回相同的数据,我想知道,两者之间有什么区别,而另一个则不能做什么? I would like to stick with only one at this point in a prototype I am creating and expand as soon as I understand Symfony2's ways of doing things more. 在此我只想坚持一个我正在创建和扩展的原型中的原型,因为我了解Symfony2的更多工作方式。 Here is the CRUD code from Symfony2: 这是Symfony2的CRUD代码:

/**
 * Lists all User entities.
 *
 * @Route("/", name="user")
 * @Method("GET")
 * @Template()
 */
public function indexAction()
{
    $em = $this->getDoctrine()->getManager();

    $entities = $em->getRepository('SomethingWebServicesBundle:User')->findAll();

    return array(
        'entities' => $entities,
    );
}

By changing this method name, I get a FOSRestController (with the configuration done correctly) 通过更改此方法名称,我得到了FOSRestController(正确完成了配置)

// "get_users"     [GET] /users

public function getUsersAction()
{
    $em = $this->getDoctrine()->getManager();

    $entities = $em->getRepository('SomethingWebServicesBundle:Users')->findAll();

    return array(
        'entities' => $entities,
    );
}

They are both controllers and you should use only one for the same tasks. 它们都是控制器,您应该只使用一个来完成相同的任务。

The default symfony controller is just a class with convience methods to get easy access to the most commonly needed things (for instance, creating a form, redirecting, etc.). 默认的symfony控制器只是一个具有便捷方法的类,可轻松访问最常用的东西(例如,创建表单,重定向等)。 You don't have to extend this controller, it just gives you some "extras". 您不必扩展此控制器,它只是给您一些“附加”。

The FOSRestController extends the Symfony controller and adds some convience methods when using the FOSRestBundle. FOSRestController扩展了Symfony控制器,并在使用FOSRestBundle时添加了一些简便的方法。 Again, you don't have to use it, it just simplifies the code for you. 同样,您不必使用它,它只是为您简化了代码。

So that being said, the controllers don't do anything special. 话虽如此,控制器并没有做任何特别的事情。 You can completely skip them and use your own stuff instead, a lot of people also prefer to not extend from the base controller, as it implies the Service Locator anti-pattern. 您可以完全跳过它们并使用您自己的东西,很多人还希望不从基本控制器扩展,因为这暗示了Service Locator反模式。

To get answers on what the FOSRestBundle can do, you should read their docs 要获得有关FOSRestBundle可以做什么的答案,您应该阅读他们的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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