Advertisement
Guest User

Untitled

a guest
Feb 2nd, 2017
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. $connection = {my db connection/object};
  2.  
  3. function PassedIn($connection) { ... }
  4.  
  5. function PassedByReference(&$connection) { ... }
  6.  
  7. function UsingGlobal() {
  8. global $connection;
  9. ...
  10. }
  11.  
  12. class ResourceManager {
  13. private static $DB;
  14. private static $Config;
  15.  
  16. public static function get($resource, $options = false) {
  17. if (property_exists('ResourceManager', $resource)) {
  18. if (empty(self::$$resource)) {
  19. self::_init_resource($resource, $options);
  20. }
  21. if (!empty(self::$$resource)) {
  22. return self::$$resource;
  23. }
  24. }
  25. return null;
  26. }
  27.  
  28. private static function _init_resource($resource, $options = null) {
  29. if ($resource == 'DB') {
  30. $dsn = 'mysql:host=localhost';
  31. $username = 'my_username';
  32. $password = 'p4ssw0rd';
  33. try {
  34. self::$DB = new PDO($dsn, $username, $password);
  35. } catch (PDOException $e) {
  36. echo 'Connection failed: ' . $e->getMessage();
  37. }
  38. } elseif (class_exists($resource) && property_exists('ResourceManager', $resource)) {
  39. self::$$resource = new $resource($options);
  40. }
  41. }
  42. }
  43.  
  44. function doDBThingy() {
  45. $db = ResourceManager::get('DB');
  46. if ($db) {
  47. $stmt = $db->prepare('SELECT * FROM `table`');
  48. etc...
  49. }
  50. }
  51.  
  52. class MyClass {
  53. protected $_db;
  54.  
  55. public function __construct($db)
  56. {
  57. $this->_db = $db;
  58. }
  59.  
  60. public function doSomething()
  61. {
  62. $this->_db->query(...);
  63. }
  64. }
  65.  
  66. class SomeClass
  67. {
  68. protected $dbc;
  69.  
  70. public function __construct($db)
  71. {
  72. $this->dbc = $db;
  73. }
  74.  
  75. public function getDB()
  76. {
  77. return $this->dbc;
  78. }
  79.  
  80. function read_something()
  81. {
  82. $db = getDB();
  83. $db->query();
  84. }
  85. }
  86.  
  87. function read_something()
  88. {
  89. $db = System::getDB();
  90. $db->query();
  91. }
  92.  
  93. function usingFunc() {
  94. $connection = getConnection();
  95. ...
  96. }
  97.  
  98. function getConnection() {
  99. static $connectionObject = null;
  100. if ($connectionObject == null) {
  101. $connectionObject = connectFoo("whatever","connection","method","you","choose");
  102. }
  103. return $connectionObject;
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement