mvc 中的模型(最佳实践,PHP)

2024-05-10

我知道有很多关于 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');

或者也许我完全错了,应该以一种完全不同的方式度过?

谢谢你!


看看您的两个解决方案,问问自己 - 如果您想开始添加越来越多的查找类型(按作者、标题、日期),会发生什么。它们应该属于书籍模型吗? (Amodel是一本书的代表)。我的答案是“不”。

Book 类应该是您的书的表示(标题、页数、文本等)——在本例中存储在数据库中。

在我看来,你的第一种方法是最好的方法 - 将查找一本书的业务逻辑分离到一个单独的对象中(按照你的惯例,我建议像BookLookupService),它负责查找书籍实例,例如:

interface IBookLookupService {
    findBookByTitle($bookTitle);
    findBooksByAuthor($authorName);
    getAllBooks();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

mvc 中的模型(最佳实践,PHP) 的相关文章

随机推荐