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

Is it possible to defer a DB connection using \Phalcon\Mvc\Model until a query is made?

I don't see any documentation that supports this feature, but it would be awesome if I could defer the connection to the database until a query is actually made.

The way I'm using \Phalcon\Mvc\Model in one instance it would drastically improve performance.

So basically it would be a connection on-demand, instead of when instantiating an instance of a model.

How it will increase performace, if the whole process from bootstrapping to showing output is a single piece? No difference if it will connecting at the beggining or in the middle of code execution...

Another question, if depending on your code parts, DB connection not always is required. In that case, do not use FactoryDefault() (https://docs.phalcon.io/4.0/en/di#factory-default), but declare and init each service separately.

edited Jan '20

Thanks, I will look into not using FactoryDefault()

The easiest way I can explain is that on one of my models it does not need a db connection on the frontend but it does need it on the backend, so my site is slightly faster if it doesn't connect to its db on frontend.

I'd consider this a "micro-optimization". Unless you're experiencing thousands of concurrent users, the performance increase will be negligible. Honestly, I wouldn't waste your time on something like this. You can get better performance for less effort elsewhere.

Dylan, that is a good point. However, its also to remove the dependency on that connection as its not considered mission critical in my case. It hadn't occured to me it was even connecting to the db since it wasn't doing any queries.

I still believe this is a valid and useful feature that I would imagine to be realtively simple to implement, but I've already refactored the problem away so no worries.