Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> Tworzenie obiektu wewnątrz innej klasy.
yayco
post 17.02.2013, 17:01:33
Post #1





Grupa: Zarejestrowani
Postów: 32
Pomógł: 2
Dołączył: 22.01.2008

Ostrzeżenie: (0%)
-----


Witam,
zaczynam pisać pewną aplikację (prosty CMS do pisania artykułów), dodam iż celem jest tylko zdobycie wiedzy i doświadczenia w OOP.

Program: posiadam dwie klasy, jedna łaczy się z bazą danych, druga jest odpowiedzialna za dodawanie artykułow do bazy. Czy tworzenie obiektu oConnectionClass wewnątrz klasy ArticleClass to jest dobrym rozwiązaniem? Wiem, ze napewno można to zrobić inaczej ale to rozwiązanie tez działa.


Mam klasę do połączenia z bazą MySql:
  1. class ConnectionClass {
  2. public $connection;
  3. protected $dns = 'mysql:host=localhost;dbname=projekt';
  4. protected $username = 'root';
  5. protected $password = '';
  6.  
  7. public function openConnection()
  8. {
  9. try {
  10. $this->connection = new PDO($this->dns, $this->username, $this->password);
  11. }
  12. catch (PDOException $e) {
  13. echo $e->getMessage();
  14. file_put_contents('log/PDOErrors.txt', $e->getMessage() . "\n", FILE_APPEND | LOCK_EX);
  15. }
  16. }
  17.  
  18. public function closeConnection(){
  19. if($this->connection != null){
  20. $this->connection = null;
  21. }
  22. }
  23. }



A tutaj mam klasę ArticleClass:
  1. class ArticleClass {
  2. public $topic;
  3. public $content;
  4. public $author;
  5. public $posted;
  6. public $category;
  7. public $tags = array();
  8.  
  9. public function __construct($topic,$content,$author,$category,$tags) {
  10. $this->topic = $topic;
  11. $this->content = $content;
  12. $this->author = $author;
  13. $this->posted = date ("Y-m-d H:i:s"); //format daty zgodny z MySQL DATETIME.
  14. $this->category = $category;
  15. $this->tags = $tags;
  16. }
  17.  
  18. public function SaveArticle() {
  19. require 'class/ConnectionClass.php';
  20. $oConnectionClass = new ConnectionClass();
  21. $oConnectionClass->openConnection();
  22.  
  23. $sql = 'INSERT INTO articles (article_topic,article_content,article_author,article_posted,article_categor
    y,article_tags)
  24. VALUES (:article_topic,:article_content,:article_author,:article_posted,:article_ca
    tegory,:article_tags)'
    ;
  25. $stmt = $oConnectionClass->connection->prepare($sql);
  26. $stmt->execute(array(
  27. ':article_topic' => $this->topic,
  28. ':article_content' => $this->content,
  29. ':article_author' => $this->author,
  30. ':article_posted' => $this->posted,
  31. ':article_category' => $this->category,
  32. ':article_tags' => $this->tags)
  33. );
  34. echo "Zapisano";
  35.  
  36. $oConnectionClass->closeConnection();
  37. }
  38. }



Go to the top of the page
+Quote Post

Posty w temacie


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

 



RSS Wersja Lo-Fi Aktualny czas: 14.08.2025 - 11:43