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(){
}
public getOneBook($title){
$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;
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(){
}
public getOneBook($title){
$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!
source
share