In college today we made a simple forum in procedural PHP. My homework is to make it so that it’s in OOP (for comparison), this is where I’m stuck.
In OOP a class should only do one thing, right? So a Topic class should allow a topic to be created, set whether replies are allow, and get its replies…
This is what I got so far,
<?php
abstract class Thread {
protected $_name; //thread name
protected $_text;
protected $_author;
protected $_allowReplies = true;
protected $_replies = array();
function __construct($name)
{
$this->setName($name);
}
protected function setAuthor(User $author)
{
} //edited
function setAllowReplies($replies)
{
if (is_bool($replies)) {
$this->_allowReplies = $replies;
}
else
{
return false;
}
}
function setName($name)
{
$this->_name = $name;
}
function addReply($reply)
{
return $this_replies[] = $reply;
}
function makeThread() //builds up array of values to add to database
{
$values = array();
//add to database here
}
}
?>
What I don’t understand is, do I now have to create a class to add the values to the database and an abstract class to add Authors (using Type hinting .etc), or can I just do it here?
(The above class is incomplete because I got halfway and thought I was doing it wrong)
What I’m basically trying to say is, am I designing the above class correctly?
Not quite. A class gathers methods and properties that constitute an object. It is perfectly valid for an object of a particular class to be able to do more than just a single task.
You don’t need an extra class to add a thread or its values to the database (you could, though). Simply offer interfaces (i.e. methods) to the world to add and manipulate a thread.
Take the author as an example: