Models in mvc (best practices, PHP)

I know that there are many articles and questions about MVC and best practices, but I cannot find a simple example:

Suppose that I need to develop a web application in PHP, I want to do this according to the MVC pattern (without a framework). The application should have a simple CRUD of books.

From the controller I want to get all the books in my store (which are stored in the database).

How should the model be?

Something like that:

class Book {
    private $title;
    private $author;

    public function __construct($title, $author)
    {
        $this->title = $title;
        $this->author = $author;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title)
    {
        $this->title = $title;
        return this;
    }   
.
.
.


class BooksService{

    public getBooks(){
        //get data from database and return it

        //by the way, what I return here, should by an array of Books objects?
    }

    public getOneBook($title){
        //get data from database and store it into $the_title, $the_autor
        $the_book = new Book($the_title, $the_autor);
        return $the_book;
    }
.
.
.

Therefore, I call it (from the controller) the following:

$book_service = new BooksService();
$all_books = $book_service->getBooks();
$one_book = $book_service->getOneBook('title');

Or maybe it's better to have everything in the Books class, something like this:

class Book 
{
    private $title;
    private $author;

    //I set default arguments in order to create an 'empty book'...
    public function __construct($title = null, $author = null)
    {
        $this->title = $title;
        $this->author = $author;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title)
    {
        $this->title = $title;
        return this;
    }   

    public getBooks(){
        //get data from database and return it

        //and hare, what I should return? an Array?
    }

    public getOneBook($title){
        //get data from database and store it into $the_title, $the_autor
        $the_book = new Book($the_title, $the_autor);
        return $the_book;
    }
.
.
.

Therefore, I call it (from the controller) the following:

$book_obj = new Book();
$all_books = $book_obj->getBooks();
$one_book = $book_obj->getOneBook('title');

Or maybe I'm completely wrong and should be different?

Thanks!

+4
source share
2 answers

.

. . , Doctrine2 Hibernate ( )

, , . , Ruby on Rails.

, , , .

:

http://culttt.com/2014/06/18/whats-difference-active-record-data-mapper/

+3

, : , ( , , ). ? ( ). , .

Book (, , ..) - .

, - - - ( - BookLookupService), , :

interface IBookLookupService {
    findBookByTitle($bookTitle);
    findBooksByAuthor($authorName);
    getAllBooks();
}
+2

Source: https://habr.com/ru/post/1613801/


All Articles