Question

I've got a PHP function (call it funcA) that is used in multiple places, so I placed funcA (and some related functions) in a separate file that is required in other PHP files. funcA makes numerous queries on a database that is already open and used by the code that calls it. Those queries are done via an MDB2 object.

As it stands now, where funcA is called, the calling routine passes an already-connected MDB2 object pointer to it. This works fine.

What I'm wondering is if it would be better to make funcA completely self-contained by not passing the MDB2object pointer and instead having funcA require MDB2 and connect to the database with its own mdb2 object. It's more memory, more CPU cycles, and more network traffic, but is it a better practice?

Was it helpful?

Solution

"best practice" is one of those things that are almost impossible to define. However, in my view, where a function depends on something else, it's best to pass that dependency into the function - as you're doing now.

This allows your function to do whatever it does, without having to worry about finding and connecting to the database. It also allows you to test your function with a dummy database.

It's generally known as dependency injection, and widely recommended in object oriented architectures.

OTHER TIPS

Some might call it bad practice too but a solution in this situation might be the Registry pattern or a Singleton PDO class.

I don't want to start a whole discussion on the right and wrong of singletons or registries but in this case it might be the cleanest solution that doesn't involve refactoring a large part of your application.


Some really basic examples (you should really read up on the links above since understanding these patterns can save you alot of time and trouble)

// Singleton class MyPDO
// This assumes you have a singleton class extending PDO somewhere included or required
function funcA(){
    $database = MyPDO::getInstance();
    // ...
}

// Registry pattern
// This assumes that somewhere during your bootstrapping you create an 
// instance of PDO and store it in the registry so you can retrieve it 
// anywhere else later
function funcA(){
    $database = Registry::get('Database');
    // ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top