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:
class ConnectionClass { public $connection; protected $dns = 'mysql:host=localhost;dbname=projekt'; protected $username = 'root'; protected $password = ''; public function openConnection() { try { $this->connection = new PDO($this->dns, $this->username, $this->password); } catch (PDOException $e) { file_put_contents('log/PDOErrors.txt', $e->getMessage() . "\n", FILE_APPEND | LOCK_EX); } } public function closeConnection(){ if($this->connection != null){ $this->connection = null; } } }
A tutaj mam klasę ArticleClass:
class ArticleClass { public $topic; public $content; public $author; public $posted; public $category; public function __construct($topic,$content,$author,$category,$tags) { $this->topic = $topic; $this->content = $content; $this->author = $author; $this->category = $category; $this->tags = $tags; } public function SaveArticle() { require 'class/ConnectionClass.php'; $oConnectionClass = new ConnectionClass(); $oConnectionClass->openConnection(); $sql = 'INSERT INTO articles (article_topic,article_content,article_author,article_posted,article_categor
y,article_tags) VALUES (:article_topic,:article_content,:article_author,:article_posted,:article_ca
tegory,:article_tags)'; $stmt = $oConnectionClass->connection->prepare($sql); ':article_topic' => $this->topic, ':article_content' => $this->content, ':article_author' => $this->author, ':article_posted' => $this->posted, ':article_category' => $this->category, ':article_tags' => $this->tags) ); $oConnectionClass->closeConnection(); } }