Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $connection = {my db connection/object};
- function PassedIn($connection) { ... }
- function PassedByReference(&$connection) { ... }
- function UsingGlobal() {
- global $connection;
- ...
- }
- class ResourceManager {
- private static $DB;
- private static $Config;
- public static function get($resource, $options = false) {
- if (property_exists('ResourceManager', $resource)) {
- if (empty(self::$$resource)) {
- self::_init_resource($resource, $options);
- }
- if (!empty(self::$$resource)) {
- return self::$$resource;
- }
- }
- return null;
- }
- private static function _init_resource($resource, $options = null) {
- if ($resource == 'DB') {
- $dsn = 'mysql:host=localhost';
- $username = 'my_username';
- $password = 'p4ssw0rd';
- try {
- self::$DB = new PDO($dsn, $username, $password);
- } catch (PDOException $e) {
- echo 'Connection failed: ' . $e->getMessage();
- }
- } elseif (class_exists($resource) && property_exists('ResourceManager', $resource)) {
- self::$$resource = new $resource($options);
- }
- }
- }
- function doDBThingy() {
- $db = ResourceManager::get('DB');
- if ($db) {
- $stmt = $db->prepare('SELET * FROM `table`');
- etc...
- }
- }
- function read_something()
- {
- $db = getDB();
- $db->query();
- }
- function read_something()
- {
- $db = System::getDB();
- $db->query();
- }
- class MyClass {
- protected $_db;
- public function __construct($db)
- {
- $this->_db = $db;
- }
- public function doSomething()
- {
- $this->_db->query(...);
- }
- }
- function usingFunc() {
- $connection = getConnection();
- ...
- }
- function getConnection() {
- static $connectionObject = null;
- if ($connectionObject == null) {
- $connectionObject = connectFoo("whatever","connection","method","you","choose");
- }
- return $connectionObject;
- }
Add Comment
Please, Sign In to add comment