Hi Paul, Great questions—moving from CI3 to CI4 can definitely bring a few surprises, especially around things like autoloading and database connection handling. Let me try to address your concerns one by one:
1) Does the $db
connection persist between controllers during a session?
No, it
doesn't persist across controllers or requests like a session variable might. When a user is redirected to another controller, a
new request lifecycle begins, and so the $db variable from the previous controller isn’t carried over. CI4 does handle connection pooling behind the scenes, but your $db variable won’t “follow” the user across controllers—you’ll need to reconnect in each place you use it (e.g., in your constructor).
2) Should you check for an existing connection before creating one?
CI4’s database library handles
connection reuse internally. When you do:
Code:
$db = \Config\Database::connect();
It doesn’t necessarily open a
new connection every time—it reuses an existing one if possible (by default it uses the default group and keeps track). So generally,
you don’t need to manually check for an existing connection. Just call connect() when you need it. That said, you can store the $db instance in a base controller or a shared service if you want to avoid repetitive code.
3) Should you disconnect after each DB interaction?
Generally,
you don’t need to manually disconnect—CI4 closes connections at the end of the request lifecycle automatically. But if you’re doing something like long-running scripts or explicitly want to close it for resource reasons, you can do:
But use it cautiously. Manually closing connections mid-request can cause errors if you try to access the DB again after that.
4) Is freeResult()
(or freeQuery()
) useful in CI4?
CI4’s Result objects automatically free the result set once the object is destroyed, so
you usually don’t need to call freeResult()
manually. However, if you're running multiple heavy queries in a single request and want to be memory-efficient, you can do something like:
Code:
$query = $db->query("SELECT ...");
// Use $query->getResult() or whatever you need
$query->freeResult();
// Optional but helpful if you're done with it
Just make sure you don’t try to use the result object afterward.
Extra Tip: Make Use of Models Where Possible
In CI4, the
Model layer is much more powerful—it can help encapsulate DB logic cleanly and automatically uses the DB connection when you extend CodeIgniter\Model. That way, you don't need to manually call connect() unless you have custom DB logic.
Hope this helps clear things up! You're definitely on the right track, and it's great that you're thinking about connection management early—many don’t until they hit those MySQL 151 connection errors! ?
Cheers!