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

Why "db" is not "shared" by default in DI?

Maybe its strange, but many time I see, its:

$di->set('db', function()

it means, it alway creates another connection whenever its getted. Shouldnt it be:

$di->setShared('db', function()

then? Or is there any pitfall?

Even if you use Shared service for DB, it will act as singleton only during your applicaion lifecycle / request-response in other words. But if you need to talk to the database server on mupltiple spots in the backend, that it would be wise to use shared service.

That's my opinion on this, let's hear others too..



34.6k
Accepted
answer

Isolated transactions require this service to be non-shared, without this, that component would not work out of the box.

Isolated transactions require separate database connection, everyting should be 'dedicated'. But, if we don't use transactions at all, we are fine with DB layer as a Shared service I guess. There's no point to open new connection if your app will have multiple calls to the DB.