PHP OOP Design Framework

My questions relate to these three examples that I have outlined for a better understanding of how to use OOP.

class Book {
    //not using getters/setters to save some space
    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);
    }

    //or just stick with this method in this class
    public function getNumReadsOfBook($name)
    {
        return (
                $this->db->query("SELECT COUNT ... WHERE name = $name")
                +
                API::getNumReadsOfABook($name)
        );
    }
}

//get number of reads of a book
$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, "" , , . ?

+5
2

, /. SQL . , PDO, MySQLi ..

, .

+1

, BookNumRead .

, __construct() , .

:

class Book {
    //not using getters/setters to save some space
    public $name;
    public $numreads;
}

class Book {
    //not using getters/setters to save some space
    public $name;
    public $numreads;

    public function __construct($id)
    {
        $this->db->query("SELECT COUNT ... WHERE name = $book->name");
        // Use return value to get number of times book is read...
        $this->numreads=$countFromDatabase;
    }
}

= new Book($id);, , .

( )

0

All Articles