Model View Controller(MVC) in PHP

The model view controller pattern is the most used pattern for today’s world web applications. It has been used for the first time in Smalltalk and then adopted and popularized by Java. At present there are more than a dozen PHP web frameworks based on MVC pattern.

Despite the fact that the MVC pattern is very popular in PHP, is hard to find a proper tutorial accompanied by a simple source code example. That is the purpose of this tutorial.

      The MVC pattern separates an application in 3 modules: Model, View and Controller:
  • The model is responsible to manage the data; it stores and retrieves entities used by an application, usually from a database, and contains the logic implemented by the application.
  • The view (presentation) is responsible to display the data provided by the model in a specific format. It has a similar usage with the template modules present in some popular web applications, like wordpress, joomla, …
  • The controller handles the model and view layers to work together. The controller receives a request from the client, invokes the model to perform the requested operations and sends the data to the View. The view formats the data to be presented to the user, in a web application as an html output.

The above figure contains the MVC Collaboration Diagram, where the links and dependencies between figures can be observed:

Our short php example has a simple structure, putting each MVC module in one folder:

Controller

The controller is the first thing which takes a request, parses it, initializes and invoke the model and takes the model response and sends it to the presentation layer. It’s practically the liant between the Model and the View, a small framework where Model and View are plugged in. In our naive php implementation the controller is implemented by only one class, named unexpectedly controller. The application entry point will be index.php. The index php file will delegate all the requests to the controller:

// index.php file
include_once("controller/Controller.php");

$controller = new Controller();
$controller->invoke();

Our Controller class has only one function and the constructor. The constructor instantiates a model class and when a request is done, the controller decides which data is required from the model. Then it calls the model class to retrieve the data. After that it calls the corresponding passing the data coming from the model. The code is extremely simple. Note that the controller does not know anything about the database or about how the page is generated.

include_once("model/Model.php");

class Controller {
     public $model;    

     public function __construct()
     {
          $this->model = new Model();
     } 

     public function invoke()
     {
          if (!isset($_GET[‘book‘]))
          {
               // no special book is requested, we‘ll show a list of all available books
               $books = $this->model->getBookList();
               include ‘view/booklist.php‘;
          }
          else
          {
               // show the requested book
               $book = $this->model->getBook($_GET[‘book‘]);
               include ‘view/viewbook.php‘;
          }
     }
}

In the following MVC Sequence Diagram you can observe the flow during a http request:

Model and Entity Classes

      The Model represents the data and the logic of an application, what many calls business logic. Usually, it’s responsible for:
  • storing, deleting, updating the application data. Generally it includes the database operations, but implementing the same operations invoking external web services or APIs is not an unusual at all.
  • encapsulating the application logic. This is the layer that should implement all the logic of the application. The most common mistakes are to implement application logic operations inside the controller or the view(presentation) layer.

In our example the model is represented by 2 classes: the “Model” class and a “Book” class. The model doesn’t need any other presentation. The “Book” class is an entity class. This class should be exposed to the View layer and represents the format exported by the Model view. In a good implementation of the MVC pattern only entity classes should be exposed by the model and they should not encapsulate any business logic. Their solely purpose is to keep data. Depending on implementation Entity objects can be replaced by xml or json chunk of data. In the above snippet you can notice how Model is returning a specific book, or a list of all available books:

include_once("model/Book.php");

class Model {
    public function getBookList()
    {
        // here goes some hardcoded values to simulate the database
        return array(
            "Jungle Book" => new Book("Jungle Book", "R. Kipling", "A classic book."),
            "Moonwalker" => new Book("Moonwalker", "J. Walker", ""),
            "PHP for Dummies" => new Book("PHP for Dummies", "Some Smart Guy", "")
        );
    }

    public function getBook($title)
    {
        // we use the previous function to get all the books and then we return the requested one.
        // in a real life scenario this will be done through a db select command
        $allBooks = $this->getBookList();
        return $allBooks[$title];
    }

}

In our example the model layer includes the Book class. In a real scenario, the model will include all the entities and the classes to persist data into the database, and the classes encapsulating the business logic.

class Book {
    public $title;
    public $author;
    public $description;

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

View (Presentation)

The view(presentation layer)is responsible for formating the data received from the model in a form accessible to the user. The data can come in different formats from the model: simple objects( sometimes called Value Objects), xml structures, json, …

The view should not be confused to the template mechanism sometimes they work in the same manner and address similar issues. Both will reduce the dependency of the presentation layer of from rest of the system and separates the presentation elements(html) from the code. The controller delegates the data from the model to a specific view element, usually associated to the main entity in the model. For example the operation “display account” will be associated to a “display account” view. The view layer can use a template system to render the html pages. The template mechanism can reuse specific parts of the page: header, menus, footer, lists and tables, …. Speaking in the context of the MVC pattern

In our example the view contains only 2 files one for displaying one book and the other one for displaying a list of books.

<html>
<head></head>

<body>

    <?php 

        echo ‘Title:‘ . $book->title . ‘<br/>‘;
        echo ‘Author:‘ . $book->author . ‘<br/>‘;
        echo ‘Description:‘ . $book->description . ‘<br/>‘;

    ?>

</body>
</html>

booklist.php

<html>
<head></head>

<body>

    <table>
        <tbody><tr><td>Title</td><td>Author</td><td>Description</td></tr></tbody>
        <?php 

            foreach ($books as $title => $book)
            {
                echo ‘<tr><td><a href="index.php?book=‘.$book->title.‘">‘.$book->title.‘</a></td><td>‘.$book->author.‘</td><td>‘.$book->description.‘</td></tr>‘;
            }

        ?>
    </table>

</body>
</html>

The above example is a simplified implementation in PHP. Most of the PHP web frameworks based on MVC have similar implementations, in a much better shape. However, the possibility of MVC pattern are endless. For example different layers can be implemented in different languages or distributed on different machines. AJAX applications can implements the View layer directly in Javascript in the browser, invoking JSON services. The controller can be partially implemented on client, partially on server…

      This post should not be ended before enumerating the advantages of Model View Controller pattern:
  • the Model and View are separated, making the application more flexible.
  • the Model and view can be changed separately, or replaced. For example a web application can be transformed in a smart client application just by writing a new View module, or an application can use web services in the backend instead of a database, just replacing the model module.
  • each module can be tested and debugged separately.
时间: 2024-10-25 09:19:45

Model View Controller(MVC) in PHP的相关文章

MVC模式(Model View Controller)下实现数据库的连接,对数据的删,查操作

MVC模式(Model View Controller): Model:DAO模型 View:JSP  在页面上填写java代码实现显示 Controller:Servlet 重定向和请求的转发: 若目标的相应页面不需要从request里面读取任何信息,则可以使用重定向,可以防止表单重复提交: ------------------------------------------------------------------------------------------------ Stude

QT Model View Controller 使用和认识

MVC全称是 Model View Controller,是一种非常非常流行的架构模式,相关MVC具体的,网上已经非常非常详尽了,不赘述了. 关于Qt中的MVC 其实Qt中的MVC并不叫MVC,而是叫"MVD",Qt中没有Controller的说法,而是使用了另外一种抽象: Delegate (委托) ,其行为和传统的MVC是相同的.写过C#的同学肯定对delegate就不陌生了,这里delegate的用法就是负责协调Model和View之间的数据.其思想如下图所示: Model是唯一

Model View Controller

On the iPhone or iPod touch, a modal view controller takes over the entire screen. This is the defaultbehavior and the only possibility on these devices. On the iPad, you have two additional options: aform sheet style and a page sheet style. You can

MVC(Model.view,Controller)

(一)MVC javabean :符合某种规范的java组件,也就是java类 Model 模型,操作数据的业务处理层,并独立于表现层. View 视图,通过客户端数据类型显示数据,并回显模型层的执行结果. Conroller 控制器.视图层和模型层的桥梁,控制数据的流向,接受视图层发出的事件,并重绘视图. [个人理解:mvc设计模式当中,Model是模型层,用于管理数据,操作数据,View是视图层,是页面显示后的效果,Conroller是控制层,用来控制执行怎样的操作,例如增删改查,然后执行成

5.Qt model view设计模式

Introduction to Model/View Programming QT4 介绍了一系列新的 Item View 类,这些类使用Model/View结构来管理数据和数据如何呈现给用户.这种结构使程序员更加灵活的开发和定制呈现数据界面,Model/View结构提供标准的Model接口让各种数据资源都能够被存在的Item View使用. The model/view architecture MVC是一种源于 smalltalk的设计模式,经常用来构建应用程序界面. MVC有3个对象构成.

Qt的Model/View Framework解析(数据是从真正的“肉(raw)”里取得,Model提供肉,所以读写文件、操作数据库、网络通讯等一系列与数据打交道的工作就在model中做了)

最近在看Qt的Model/View Framework,在网上搜了搜,好像中文的除了几篇翻译没有什么有价值的文章.E文的除了Qt的官方介绍,其它文章也很少.看到一个老外在blog中写道Model/View是他认为Qt中最不好的一部分了.真的是这样吗?为了回馈开源社区,我写了这篇blog,写的是我认为比较有价值的东东.题目起得是解析,但也没有特别细节的介绍,点到为止,有兴趣的Tx可以继续讨论.我所看的资料有<C++ GUI Programming with Qt 4, Second Edition

QT MVC 技术Model/View初探

Model/View实现表格技术 [+] 一.简介 Model/View结构使数据管理与相应的数据显示相互独立,并提供了一系列标准的函数接口和用于Model模块与View模块之间的通信.它从MVC演化而来,MVC由三种对象组成,Model是应用程序对象,View是它的屏幕表示,Controller定义了用户界面如何对用户输入进行响应.把MVC中的View和Controller合在一起,就形成了Model/View结构. 二.运行图 (1)为了灵活对用户的输入进行处理,引入了Delegate,Mo

iOS开发——笔记篇&amp;关于字典plist读取/字典转模型/自定义View/MVC/Xib的使用/MJExtension使用总结

关于字典plist读取/字典转模型/自定义View/MVC/Xib的使用/MJExtension使用总结 一:Plist读取 1 /******************************************************************************/ 2 一:简单plist读取 3 4 1:定义一个数组用来保存读取出来的plist数据 5 @property (nonatomic, strong) NSArray *shops; 6 7 2:使用懒加载的方

Qt Model/View(转)

介绍 Qt 4推出了一组新的item view类,它们使用model/view结构来管理数据与表示层的关系.这种结构带来的功能上的分离给了开发人员更大的弹性来定制数据项的表示,它也提 供一个标准的model接口,使得更多的数据源可以被这些item view使用.这里对model/view的结构进行了描述,结构中的每个组件都进行了解释,给出了一些例子说明了提供的这些类如何使用. Model/View 结构 Model-View-Controller(MVC), 是从Smalltalk发展而来的一种