We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

When to use set() and when setShared() for service definition? Does it really matter?

Hey guys,

Was wondering today which services should be set as shared and which not. I think other users will find this topic useful too. Does it really matter for performance or anything else?

According to DI docs

Services can be registered as “shared” services this means that they always will act as singletons. Once the service is resolved for the first time the same instance of it is returned every time a consumer retrieve the service from the container

Looking at Vokuro Service file some are set as shared and some not. Can someone give examples of common services and what will be the better way to set them? For example DB, sesssion, url, router, view and so on.

Thanks!



79.0k
Accepted
answer
edited Nov '16

IMHO, shared services are better for some types of components while for others it's better to stick with non-shared. For DB service/component, if you use transactions, you'll need to use non-shared service. For regular web apps w/o transactions, shared DB service is better performing as it will keep alive socket connection during entire application lifecycle.

I always tend to use shared services, unless there's a very specific requirement where your business logic requires new object instance each time.