My questions relate to these three examples that I have outlined for a better understanding of how to use OOP.
class Book {
public $name;
public $numreads;
}
class BookFactory {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
public function getBook($id) {
$book = new Book();
$book->name = $db->query("SELECT name FROM books...");
$booknumreads = new BookNumRead($this->db, $book);
$book->numreads = $booknumreads->getFromLocal() + $booknumreads->getFromAnotherSource();
return $book;
}
}
class BookNumRead {
private $db;
private $book;
public function __construct(Database $db, Book $book) {
$this->db = $db;
$this->book = $book;
}
public function getFromLocal()
{
return $this->db->query("SELECT COUNT ... WHERE name = $book->name");
}
public function getFromAnotherSource()
{
return API::getNumReadsOfABook($book->name);
}
public function getNumReadsOfBook($name)
{
return (
$this->db->query("SELECT COUNT ... WHERE name = $name")
+
API::getNumReadsOfABook($name)
);
}
}
$db = new Database();
$bookfactory = new BookFactory($db);
$book = $bookfactory->getBook(123);
echo $book->getNumReads();
First of all, is this a good approach to OOP?
These classes are completely different. Vs Value Domain Objects? For example, in my application there can be as many book objects as I need. BookFactory, however, as a service in my application, there can only be one in my application, but I may need this class from many other places in my application, should I put it as an object in the ServiceLocator / ServiceContainer?
BookNumRead ServiceLocator/ServiceContainer getNumReadsOfBook() Book, ?
, , BookFactory:: getBook(), ( BookFactory), ,
messy, beacasue, "" , , . ?