1

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);

Scott
  • 432
  • 5
  • 21
  • Related: [MySQLi class pattern for connection, close, leave open?](http://stackoverflow.com/questions/8312991/mysqli-class-pattern-for-connection-close-leave-open) – hakre Dec 02 '11 at 03:03

1 Answers1

1

You're best bet is to store it in a variable with that is accessible globally.

Traditionally you'd store the variable in the global namespace, though this is frowned upon now a days.

Instead of using a singleton, what you should do is place the object into a registry like Zend_Registry.

Simply put, you just need to create a class with two static members; set($key, $value) and get($key). When you construct your PDO object just call set('db', $pdoConnection) to store it and when you need to access the database, call get('db').

Community
  • 1
  • 1
hafichuk
  • 8,680
  • 9
  • 32
  • 52
  • what makes `Zend_Registry` different to `$GLOBALS['registry'][db] = $pdoConnection;`? – hakre Dec 02 '11 at 02:52
  • @hakre Its an object so it encapsulates the state of the registry. In theory you could add extra functionality (like logging) in the `get` and `set` calls. You can't do that with the vanilla $GLOBALS array. – hafichuk Dec 02 '11 at 03:21
  • Sure, put something into `$GLOBALS['registry']` with `ArrayAccess`, e.g. a write once, read many hash. – hakre Dec 02 '11 at 03:23
  • @hakre You should post this as an alternative answer. `ArrayAccess` seems like it would be a good base for a simple registry object. – hafichuk Dec 02 '11 at 04:18