Advertisement
Guest User

Untitled

a guest
Aug 10th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 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. protected $dbc;
  68.  
  69. public function __construct($db) {
  70. $this->dbc = $db;
  71. }
  72.  
  73. public function getDB() {
  74. return $this->dbc;
  75. }
  76.  
  77. function read_something() {
  78. $db = getDB();
  79. $db->query();
  80. }
  81. }
  82.  
  83. function read_something() {
  84. $db = System::getDB();
  85. $db->query();
  86. }
  87.  
  88. function usingFunc() {
  89. $connection = getConnection();
  90. ...
  91. }
  92.  
  93. function getConnection() {
  94. static $connectionObject = null;
  95. if ($connectionObject == null) {
  96. $connectionObject = connectFoo("whatever","connection","method","you","choose");
  97. }
  98. return $connectionObject;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement