Pass via constructor or Registry. IMO, where a database connection is needed it usually indicates the need for a Model class which encapsulates a model of the data being manipulated/read/written. For example, have a generic set of classes which handle database reading/writing, but on top of those generate some classes with a pretty simple interface.
Best sources to look for are pattern descriptions of Data Mapper, Row Date and Table Data Gateway, Data Objects (I have a tutorial here on the forum for that one which I intentionally simplified to serve as an introduction), ORM.
In my source code I have a Model class (API changes a lot between apps and packages) like:
Code: Select all
$user = new User;
$user->name = 'Pádraic';
$user->save();
Code: Select all
$user = new User;
$user->findFirst(array('name'=>'Pádraic'));
echo $user->name; // Pádraic
Overall point is that User encapsulates the database connection (say PDO) which is sourced from a Registry. Because my application code is unaware of the connection object, and only knows about User and it's simple interface, I don't need to pass the Database object everywhere. In fact, I could replace PDO with MDB2 or ADOdb and it would never know the difference. The second benefit is that by using Model classes, I now have a small collection of objects where any database changes are isolated - I could edit User to use an ADOdb object, or MDB2 object, pretty easily. Even better, User could extend a common "Model" class where the database stuff is handled in one single manageable class.
Worth noting it's considered good practice to make use of Model style solutions - they keep the application code independent of any database access solution, can carry the weight of business logic ($user->findActiveUsers()), and reduce the amount of data manipulation, sorting and filtering application code tends to collect. It can be inefficient since simple solutions assume one object per database row which has led to ever more complex solutions from Data Mappers (which are not bad) to full-blown ORMs like Propel. Sometimes accessing SQL directly in some scenarios is far more efficient, esp. if it improves performance substantially.
I'd say do some reading, see what others say here, and maybe experiement with a few possible Model solutions to see how they fit.