Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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



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