我知道有很多关于 MVC 和最佳实践的文章和问题,但我找不到这样的简单示例:
假设我必须用 PHP 开发一个 Web 应用程序,我想遵循 MVC 模式(没有框架)。
该应用程序应该有一个简单的书籍 CRUD。
我想从控制器获取我商店中的所有书籍(保存在数据库中)。
模型应该怎样?
像这样的事情:
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;
}
.
.
.
所以我这样称呼它(从控制器):
$book_service = new BooksService();
$all_books = $book_service->getBooks();
$one_book = $book_service->getOneBook('title');
或者也许最好将所有内容都放在 Books 类中,如下所示:
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;
}
.
.
.
所以我这样称呼它(从控制器):
$book_obj = new Book();
$all_books = $book_obj->getBooks();
$one_book = $book_obj->getOneBook('title');
或者也许我完全错了,应该以一种完全不同的方式度过?
谢谢你!