Guest User

Untitled

a guest
Jun 29th, 2018
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 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('SELET * FROM `table`');
  48. etc...
  49. }
  50. }
  51.  
  52. function read_something()
  53. {
  54. $db = getDB();
  55. $db->query();
  56. }
  57.  
  58. function read_something()
  59. {
  60. $db = System::getDB();
  61. $db->query();
  62. }
  63.  
  64. class MyClass {
  65. protected $_db;
  66.  
  67. public function __construct($db)
  68. {
  69. $this->_db = $db;
  70. }
  71.  
  72. public function doSomething()
  73. {
  74. $this->_db->query(...);
  75. }
  76. }
  77.  
  78. function usingFunc() {
  79. $connection = getConnection();
  80. ...
  81. }
  82.  
  83. function getConnection() {
  84. static $connectionObject = null;
  85. if ($connectionObject == null) {
  86. $connectionObject = connectFoo("whatever","connection","method","you","choose");
  87. }
  88. return $connectionObject;
  89. }
Add Comment
Please, Sign In to add comment