【发布时间】:2015-10-30 09:07:24
【问题描述】:
我知道有很多关于 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');
或者也许我完全错了,应该以非常不同的方式?
谢谢!
【问题讨论】: