Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: Klasa bazy danych.
Forum PHP.pl > Forum > PHP > Object-oriented programming
Flaku
Witam,

Jestem początkujący w php5, Przeszukałem neta i znalazłem parę przydatnych rzeczy skleiłem je w całość w wyszła cała klasa. Jednak nie wiem czy jest ona dobrze napisana, mógł by mi to ktoś sprawdzić ? Poniżej załanczam klasę. Z góry dziękuje za pomoc.

  1. <?
  2. # ----------------------------------------
  3. # Sterownik bazy MySQL
  4. # ----------------------------------------
  5.  
  6. define("CACHE_DIR", "./sql_cache/");
  7.  
  8. class Sql 
  9. {
  10. public $cid;
  11. public $queryResult = array();
  12. public $queries = 0;
  13. public $rows = array(0=>array());
  14. public $cache_state = 0;
  15. public $cache_file;
  16. public $cache_buffer;
  17. public $cache_ptr;
  18.  
  19. public function __construct($host, $username, $password, $database) 
  20. {
  21. $this -> cid = mysql_connect($host, $username, $password) or die ($this -> error("Problem z nawiazaniem polaczenia"));
  22. mysql_select_db($database, $this -> cid) or die ($this -> error("Problem z wybraniem bazy"));
  23. } // end __construct();
  24.  
  25. public function sqlClose() 
  26. {
  27. mysql_close($this -> cid);
  28. } // end sqlClose();
  29.  
  30. public function sqlCache($handle = 0) 
  31. {
  32. if(is_string($handle)) 
  33. {
  34. if(file_exists(CACHE_DIR.'cache_'.$handle.'.sql')) 
  35. {
  36. $this -> cache_state = 1;
  37. $this -> cache_ptr = 0;
  38. $this -> cache_buffer = unserialize(file_get_contents(CACHE_DIR.'cache_'.$handle.'.sql'));
  39. } 
  40. else 
  41. {
  42. $this -> cache_state = 2;
  43. $this -> cache_buffer = array();
  44. $this -> cache_file = CACHE_DIR.'cache_'.$handle.'.sql';
  45. }
  46. } 
  47. else 
  48. {
  49. if($this -> cache_state == 2) 
  50. {
  51. file_put_contents($this -> cache_file, serialize($this -> cache_buffer));
  52. }
  53. $this -> cache_state = 0;
  54. }
  55. } // end sql_cache();
  56.  
  57. public function sqlCacheRemove($handle) 
  58. {
  59. if(file_exists(CACHE_DIR.'cache_'.$handle.'.sql')) 
  60. {
  61. unlink(CACHE_DIR.'cache_'.$handle.'.sql');
  62. }
  63. } // end sql_cache_remove();
  64.  
  65. public function error($what = "Main System Error With Data Base") 
  66. {
  67. return "<p style=\"color: red; font-weight: bold\">Driver SQL Problem <br>" . $what . " </p> ".mysql_error();
  68. } // end error();
  69.  
  70. public function query($to_query, $query_name) 
  71. {
  72. if($this -> cache_state != 1) 
  73. {
  74. $this -> queryResult[$query_name] = mysql_query($to_query, $this -> cid);
  75. $this -> queries++;
  76. return 1;
  77. }
  78. } // end query();
  79.  
  80. public function numRows($query_name) 
  81. {
  82. return mysql_num_rows($this -> queryResult[$query_name]);
  83. } // end numRows();
  84.  
  85. public function fetchRow($query_name) 
  86. {
  87. if($this -> cache_state == 1) 
  88. {
  89. if(!isset($this -> cache_buffer[$this -> cache_ptr])) 
  90. {
  91. return 0;
  92. }
  93. $this -> rows = $this -> cache_buffer[$this -> cache_ptr];
  94. $this -> cache_ptr++;
  95. return 1;
  96. } 
  97. else 
  98. {
  99. if($this -> rows[$query_name] = mysql_fetch_row($this -> queryResult[$query_name])) 
  100. {
  101. if($this -> cache_state == 2) 
  102. {
  103. $this -> cache_buffer[] = $this -> rows;
  104. }
  105. return 1;
  106. }
  107. }
  108. return 0;
  109. } // end fetchRow();
  110.  
  111. public function fetchAssoc($query_name) 
  112. {
  113. if($this -> cache_state == 1) 
  114. {
  115. if(!isset($this -> cache_buffer[$this -> cache_ptr])) 
  116. {
  117. return 0;
  118. }
  119. $this -> rows = $this -> cache_buffer[$this -> cache_ptr];
  120. $this -> cache_ptr++;
  121. return 1;
  122. } 
  123. else 
  124. {
  125. if($this -> rows[$query_name] = mysql_fetch_assoc($this -> queryResult[$query_name])) 
  126. {
  127. if($this -> cache_state == 2) 
  128. {
  129. $this -> cache_buffer[] = $this -> rows;
  130. }
  131. return 1;
  132. }
  133. }
  134. return 0;
  135. } // end fetchAssoc();
  136.  
  137. public function insertId() 
  138. {
  139. return mysql_insert_id($this -> cid);
  140. } // edn insertId();
  141.  
  142. public function affectedRows() 
  143. {
  144. return mysql_affected_rows($this -> cid);
  145. } // end affectedRows(); 
  146.  
  147. public function fetchQuery($to_query, $query_name) 
  148. {
  149. $this -> queryResult[$query_name] = mysql_query($to_query, $this -> cid);
  150. $this -> rows[$query_name] = mysql_fetch_assoc($this -> queryResult[$query_name]);
  151. $this -> queries++;
  152. } // end fetchQuery();
  153.  
  154. }
  155.  
  156. ?>
l0ud
Chodzi Ci o zgodność z ideą programowania obiektowego?

Umieść kod w znacznikach [php] a nie code. W tej chwili nie jest czytelny.
Crozin
Tak na szybko to przejzalem
1) Do obsługi błędów użyj wyjątków (Exception" title="Zobacz w manualu PHP" target="_manual)
2) Generalnie jest taka jedna zasada - jeden obiekt, ma się skupić na jednym konkretnym zadaniu - u Ciebie jeden obiekt wykonuje przynajmiej dwa - obsługę zapytań, obsługę cachea SQLa
3)
Cytat
define("CACHE_DIR", "./sql_cache/");
Skoro stała CACHE_DIR wskazuje na katalog, który jest miejscem cache'a wyłącznie SQLa (to sugeruje nazwa) to zamiast zaśmiecać globalną pamięć skorzystać z stałej klasy
  1. <?
  2. class Sql{
  3. const CACHE_DIR = './sql_cache/';
  4.  
  5. //...
  6. $file = self::CACHE_DIR . $handle;
  7. }
  8. ?>
Flaku
l0ud :

Tak


Crozin :
1. Nie wiem o c w tym chodzi, nie doszedłem z moja nauka jeszcze do tego ; )
2. Tzn. że może źle działać kiedy obiekt będzie obsługiwać 2 zadania, może zrobić 2 obiekty do jednej klasy ?
3. Nie wiem ocb ; )
Crozin
Ad. 1) http://pl2.php.net/manual/pl/language.exceptions.php
Ad. 2) Chodziło mi o to, że jedna klasa (nie jeden obiekt, jak wcześniej napisałem) powinna skupiać się na konkretnym zadaniu. A więc możesz stworzyć jedną klasę do obsługi bazy danych i drugą do obsługi cache'a.
Ad. 3) http://pl2.php.net/manual/pl/language.oop5.constants.php
Flaku
Spoko tak będę robić. Dzięki za pomoc.
matix
  1. <?php
  2. public function error($what = "Main System Error With Data Base") 
  3. {
  4. return "<p style=\"color: red; font-weight: bold\">Driver SQL Problem <br>" . $what . " </p> ".mysql_error();
  5. } // end error();
  6. ?>


Gdy wyświetlasz błąd, do klasy nie pakuj HTML-a. To robisz w szablonach strony.

  1. <?php
  2. if ($db->error())
  3.  echo '<div id="errorbox">'.$db->error().'</div>';
  4. ?>


Pzdr.
Flaku
Wiem o tym ;P na razie napisałem tylko klasę w prawdzie powiedziawszy powinienem zacząć od templatów, ale ja zawsze sobie lubię utrudniać pracę.
Crozin
Zamiast:
  1. <?php
  2. $this -> cid = mysql_connect($host, $username, $password) or die ($this -> error("Problem z nawiazaniem polaczenia"));
  3. ?>
  1. <?php
  2. $this -> cid = mysql_connect($host, $username, $password);
  3. if(!$this->cid){
  4. throw new MyMysqlException('jakisIdentyfikator', array($host, $username, $password, mysql_error()));
  5. }
  6. ?>
Zamiast:
  1. <?php
  2. $this -> queryResult[$query_name] = mysql_query($to_query, $this -> cid);
  3. ?>
  1. <?php
  2. $this -> queryResult[$query_name] = mysql_query($to_query, $this -> cid);
  3. if(!$this -> queryResult[$query_name]){
  4. throw new MyMysqlException('jakisIdentyfikator', array($to_query, mysql_error(), mysql_errno()));
  5. }
  6. ?>
Oczywiście potrzebujesz jeszcze klasę MyMysqlException, może ona wyglądać na przykład tak:
  1. <?
  2.  
  3. class MyMysqlException extends Exception{
  4. public function __construct($id, array $dodatkoweInformacje){
  5. //na podstawie $id mozesz np. przerwac dzialanie calej aplikacji, dane zapisac w l
    ogu (badz nie) itp. itd.
  6. //a w $dodatkoweInformacje masz uzyteczne informacje do debuggowania aplikacji
  7. }
  8. }
  9.  
  10. ?>
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.