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 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')
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.