How can I access a PDO connection(to mysql) in my class methods from a seperate file, without rewriting a new PDO() every time I need the connection? And without using the singleton pattern – which is apparently frowned upon?
edit:
What I’ve done in the past was created a database class and in that class assigned a $connection attribute the connection via mysql_connect in a __construct method. In the same file, I would instantiate the class so that it was ready to go. Then whenever I needed that connection I would simply require that database file and add a global $connection in the method that need the $connection. I just can’t figure out a solid way to accomplish this with new PDO($dsn, $user, $password);
You’re best bet is to store it in a variable with that is accessible globally.
Traditionally you’d store the variable in the
globalnamespace, though this is frowned upon now a days.Instead of using a
singleton, what you should do is place the object into aregistrylikeZend_Registry.Simply put, you just need to create a class with two static members;
set($key, $value)andget($key). When you construct your PDO object just callset('db', $pdoConnection)to store it and when you need to access the database, callget('db').