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

Shared/NonShared services and documentation

Hi, I'm new to Phalcon, I'm trying to get a sense about shared/non shared services and what are the best practices when defining services, so, in docs there is this table about "Service Name Conventions" which is pretty self-explanatory and straightforward, on the contrary, in tutorials and answers here in this forum, often for example, DB service is used as non shared as it is otherwise suggested in the service name conventions. The shared db service it makes sense to me, non shared it could, since these two have a different meaning which one is better? or ... is it a thing related with each project architecture?

Thx



8.6k

From the documentation: "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"

https://docs.phalcon.io/en/latest/reference/di.html#shared-services

It's completly depend on your application design. Shared means a singleton — service is created just once and then this instance is used everywhere. In most of cases you can decide not to care about it and define all service as shared. Sometime it can be very important or just a good optimization, anyway it's better to learn a little more about such things as singleton, service pattern, etc and clearly understand how it works.

edited Dec '15

How do you pass an arguments to the shared service?

It seems that this is the only working syntax:

Shared service name: bladeRunner

 $this->di->getBladeRunner([0x0a, 0xff]);

I wanted to avoid refering to DI always and using magic method getSharedService...

so I did it like this:

$di->setShared('bladeRunner', function (){
    class MyOverride extends OriginalClass
    {
        function myCustomOverride($id, $data) {
        //handle data from passed arguments 
        }
    }
    return new MyOverride();
    });

Finally, call the shared service and pass some data to it, this time with much simpler syntax:

 $this->bladeRunner->myCustomOverride([0x0a, 0xff]);