Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> [PHP][OOP] Klasa do łączenia się z bazą danych - czy dobrze jest skonstruowana?
Dominator
post
Post #1





Grupa: Zarejestrowani
Postów: 565
Pomógł: 15
Dołączył: 11.10.2010

Ostrzeżenie: (20%)
X----


Witajcie
Dawno nic w php nie robiłem, więc tak dla przypomnienia zrobiłem sobie klasę, która łączy się z bazą danych. Mam takie pytanie - czy ja dobrze to zrobiłem? Co ewentualnie proponujecie zmienić?
Ogólnie to jestem w trakcie przesiadki na OOP, więc nie krzyczcie (IMG:style_emoticons/default/biggrin.gif)

  1. <?php
  2.  
  3. Class UserInterface
  4. {
  5. public function SetDBData($_server, $_port, $_username, $_password, $_database);
  6. {
  7. $this->server = $_server;
  8. $this->port = $_port;
  9. $this->user = $_username;
  10. $this->password = $_password;
  11. $this->database = $_database;
  12. }
  13. public function DBConnect()
  14. {
  15. Try
  16. {
  17. $pdo = new PDO('mysql:host='.$this->server.';dbname='.$this->database.';port='.$this->port, $this->username, $this->password );
  18. }
  19. catch(PDOException $e)
  20. {
  21. return "Error! Code ->".$e;
  22. }
  23. }
  24. }
  25.  
  26. $_UI = new UserInterface();
  27. $this->SetDBData("","","","");
  28. $this->DBConnect();
  29.  
  30. ?>
Go to the top of the page
+Quote Post
 
Start new topic
Odpowiedzi
Dominator
post
Post #2





Grupa: Zarejestrowani
Postów: 565
Pomógł: 15
Dołączył: 11.10.2010

Ostrzeżenie: (20%)
X----


Okej, pomajstrowałem i wygląda to tak:

  1. <?php
  2.  
  3. Class DB
  4. {
  5. public function Set($server, $port, $username, $password, $database)
  6. {
  7. $this->server = $server;
  8. $this->port = $port;
  9. $this->user = $username;
  10. $this->password = $password;
  11. $this->database = $database;
  12. }
  13. public function Connect()
  14. {
  15. try
  16. {
  17. $pdo = new PDO('mysql:host='.$this->server.';dbname='.$this->database.';port='.$this->port, $this->username, $this->password );
  18. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  19. if($pdo)
  20. {
  21. return "connected";
  22. }
  23. }
  24. catch(PDOException $e)
  25. {
  26. return "Error! Code ->".$e->getMessage();
  27. }
  28. }
  29. }
  30.  
  31. $db = new DB();
  32. $db->Set("","","","","");
  33. echo $db->Connect();
  34.  
  35.  
  36.  
  37. ?>


Tylko dostaję błąd: Notice: Undefined property: DB::$username in ... (17 linia)
Dlaczego?

EDIT: Poradziłem sobie, łączy się z bazą (IMG:style_emoticons/default/biggrin.gif)

Tylko pytanie: czy dobrze to jest napisane? co zmienić?

Ten post edytował Dominator 8.05.2013, 20:11:49
Go to the top of the page
+Quote Post

Posty w temacie


Reply to this topicStart new topic
2 Użytkowników czyta ten temat (2 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Aktualny czas: 15.10.2025 - 00:59