简体   繁体   中英

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.

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. In order to create all that stuff, the listAction() calls a lot of services FiltersManager , UserManager , ApiFetcher , Paginator , etc...

I want to move out (almost) all the code from listAction to some MyUsefulClass , and for that I need that class to have state. So I can see 2 options:

  • Create MyUsefulClass as a custom model class, but I need to manually create new instances of the services.
  • Define MyUsefulClass as a service so I can inject all other services, but I need to give that service a state.

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).

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.

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