I'm always confused as to which way is the best to do the following. For example, say we have two classes BlogPost and Tag, which correspond to the database tables Posts and Tags. Is it bad design to instantiate a class inside another class or should they be independent?
class BlogPost { private $db; private $title; private $description; private $tagsArray; public function __construct($db){$this->db = $db;} public function getTitle(){/*...*/} public function getDescription(){/*...*/} public function getTags(){/*...*/} public function setTitle($title){/*...*/} public function setDescription($desc){/*...*/} public function setTags($tags){/*...*/} public function addPost(){ //insert into database query //bindParams //execute $this->addTags($this->db->last_insert_id()); } public function addTags($lastInsertId){ require_once('class.Tag.php'); foreach($tagsArray as $tagItem){ $tagClass = new Tag($this->db, $lastInsertId); $tagClass->setTagName($tagItem["title"]); $tagClass->addTag(); } } } index.php
require_once('class.BlogPost.php'); $blogPost = new BlogPost($db); $blogPost->setTitle("title"); $blogPost->setDescription("description"); $blogPost->setTags($tagsArray); $blogPost->addPost(); Or is it better to keep classes independent? Like so:
class BlogPost { private $db; private $title; private $description; public function __construct($db){$this->db = $db;} public function getTitle(){/*...*/} public function getDescription(){/*...*/} public function getId(){/*...*/} public function setTitle($title){/*...*/} public function setDescription($desc){/*...*/} public function setId($id){/*...*/} public function addPost(){ //insert into database query //bindParams //execute $this->setId($this->db->last_insert_id()); } } index.php
require_once('class.BlogPost.php'); $blogPost = new BlogPost($db); $blogPost->setTitle("title"); $blogPost->setDescription("description"); $blogPost->addPost(); $lastInsertId = $blogPost->getId(); require_once('class.Tag.php'); $tagClass = new Tag($db, $lastInsertId); $tag->setTags($tagsArray); $tag->addTag(); Thanks for any info!