From 466f6bef8db25843aad3c107cacf4ec1596ee16f Mon Sep 17 00:00:00 2001 From: dmetreeves Date: Mon, 15 Jun 2020 03:01:03 +0300 Subject: [PATCH] Elegant refactoring Tried to apply tricks from the book :) --- Document.php | 77 ++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 53 insertions(+), 24 deletions(-) diff --git a/Document.php b/Document.php index 7803df6..6820d04 100644 --- a/Document.php +++ b/Document.php @@ -1,45 +1,74 @@ 5); - $this->user = $user; + /** + * Document constructor. + * @param string $name + * @param Database $db + */ + public function __construct($name, $db) + { $this->name = $name; + $this->db = $db; } - public function getTitle() { - $db = Database::getInstance(); - $row = $db->query('SELECT * FROM document WHERE name = "' . $this->name . '" LIMIT 1'); - return $row[3]; // third column in a row + public function title() + { + return $this->dbRowColumn(3); // third column in a row } - public function getContent() { - $db = Database::getInstance(); - $row = $db->query('SELECT * FROM document WHERE name = "' . $this->name . '" LIMIT 1'); - return $row[6]; // sixth column in a row + public function content() + { + return $this->dbRowColumn(6); // sixth column in a row } - public static function getAllDocuments() { - // to be implemented later + private function dbRowColumn($column) + { + $pattern = 'SELECT * FROM document WHERE name = "%s" LIMIT 1'; + $sql = sprintf($pattern, $this->name); + $row = $this->db->query($sql); + return $row[$column]; } +} +final class Documents +{ + public function all() + { + // to be implemented later + return []; + } } -class User { +final class User +{ + private $db; + + public function __construct(Database $db) + { + $this->db = $db; + } - public function makeNewDocument($name) { - $doc = new Document(); - $doc->init($name, $this); - return $doc; + public function newDocument($name) + { + return new Document($name, $this->db); } - public function getMyDocuments() { - $list = array(); - foreach (Document::getAllDocuments() as $doc) { + public function ownDocuments() + { + $list = []; + foreach ((new Documents)->all() as $doc) { if ($doc->user == $this) $list[] = $doc; }