简体   繁体   English

带或不带状态的 Symfony2 服务

[英]Symfony2 services with or without state

Pretty new to Symfony2, I've been reading that services in Symfony2 should be stateless , and I think it kind of makes sense. Symfony2 非常新,我一直在阅读Symfony2中的服务应该是无状态的,我认为这有点道理。

On the other hand, I'm trying to refactor a massive 250-line SomeController->listAction() , which creates a table of data with many filters, and 4 forms in total.另一方面,我试图重构一个庞大的 250 行SomeController->listAction() ,它创建了一个包含许多过滤器的数据表,总共有 4 个表单。 In order to create all that stuff, the listAction() calls a lot of services FiltersManager , UserManager , ApiFetcher , Paginator , etc...为了创建所有这些东西, listAction()调用了很多服务FiltersManagerUserManagerApiFetcherPaginator等......

I want to move out (almost) all the code from listAction to some MyUsefulClass , and for that I need that class to have state.我想将(几乎)所有代码从listAction到某个MyUsefulClass ,为此我需要该类具有状态。 So I can see 2 options:所以我可以看到两个选项:

  • Create MyUsefulClass as a custom model class, but I need to manually create new instances of the services.创建MyUsefulClass作为自定义模型类,但我需要手动创建服务的新实例。
  • Define MyUsefulClass as a service so I can inject all other services, but I need to give that service a state.MyUsefulClass定义为服务,以便我可以注入所有其他服务,但我需要为该服务提供一个状态。

I'd go for the 2nd option, but I don't know if I'm missing some other options, and I'm not even sure whether it's really important to keep stateless services...我会选择第二个选项,但我不知道我是否遗漏了其他一些选项,我什至不确定保持无状态服务是否真的很重要......

I ended up creating the classes that do the job as services, because I think services are one of the best things about Symfony in many ways (they have some issues though).我最终创建了作为服务来完成这项工作的类,因为我认为服务在很多方面都是 Symfony 最好的东西之一(尽管它们有一些问题)。

In order to keep my services stateless, what I did was to create another set of classes, pretty much just value objects with some properties.为了保持我的服务无状态,我所做的是创建另一组类,几乎只是具有某些属性的值对象。 These values objects hold the state I need and they are passed to (and/or returned from) the methods in my services.这些值对象保存我需要的状态,它们被传递给(和/或从)我的服务中的方法。

This approach makes me write more classes, but it makes sense to me, and I can clearly separate the code that does the job from the code that just holds some property values.这种方法让我编写了更多的类,但这对我来说很有意义,而且我可以清楚地将完成工作的代码与仅保存一些属性值的代码分开。

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

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