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.

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

  1. Model View Controller (MVC) Overview

    By Rakesh Chavda on Jul 01, 2015 What is MVC?Model View Controller is a type of user interface archi ...

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

    MVC模式(Model View Controller): Model:DAO模型 View:JSP  在页面上填写java代码实现显示 Controller:Servlet 重定向和请求的转发: 若 ...

  3. MVC(Model View Controller)框架

    MVC框架 同义词 MVC一般指MVC框架 MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一 ...

  4. 深入浅出Java MVC(Model View Controller) ---- (JSP + servlet + javabean实例)

    在DRP中终于接触到了MVC,感触是确实这样的架构系统灵活性不少,现在感触最深的就是使用tomcat作为服务器发布比IIS好多了,起码发布很简单,使用起来方便. 首先来简单的学习一下MVC的基础知识, ...

  5. What is the difference between Reactjs and Rxjs?--React is the V (View) in MVC (Model/View/Controller).

    This is really different, React is view library; and Rxjs is reactive programming library for javasc ...

  6. Model View Controller

    On the iPhone or iPod touch, a modal view controller takes over the entire screen. This is the defau ...

  7. 设计模式 --- 模型-视图-控制器(Model View Controller)

    模型-视图-控制器(Model-View-Controller,MVC)是Xerox PARC在20世纪80年代为编程语言Smalltalk-80发明的一种软件设计模式,至今已广泛应用于用户交互应用程 ...

  8. MVC4 Model View Controller分离成独立项目

    适合人群:了解MVC项目的程序员 开发工具:vs2012 开发语言:C# 小项目或功能比较单一的项目可以直接新建一个MVC基本项目类型即可,但随着需求不断迭代,项目的功能模块越来越多,甚至有些模块可以 ...

  9. Qt Model/View(官方翻译,图文并茂)

    http://doc.trolltech.com/main-snapshot/model-view-programming.html 介绍 Qt 4推出了一组新的item view类,它们使用mode ...

随机推荐

  1. Winform中Checkbox与其他集合列表类型之间进行关联

    本文提供了Checkbox与CheckedListBox.DataGridViewCheckBoxColumn等的联动关系 1.CheckboxAssociateFactroy.Create创建联动关 ...

  2. POJ 1185 炮兵阵地 (状压DP,轮廓线DP)

    题意: 给一个n*m的矩阵,每个格子中有'P'或者'H',分别表示平地和高原,平地可以摆放大炮,而大炮的攻击范围在4个方向都是2格(除了自身位置),攻击范围内不能有其他炮,问最多能放多少个炮?(n&l ...

  3. 程序员的智囊库系列之2----网站框架(framework)

    程序员的智囊库系列之2--网站框架(framework) 这是程序员的智囊库系列的第二篇文章.上一篇文章讲了服务器与运维相关的工具,这篇文章我们将介绍几个搭建网站的框架: django express ...

  4. ucos-ii核心算法分析(转)

    μC/OS-Ⅱ是一种免费公开源代码.结构小巧.具有可剥夺实时内核的实时操作系统.其 内核提供任务调度与管理.时间管理.任务间同步与通信.内存管理和中断服务等功能.适合小型控制系统,具有执行效率高.占用 ...

  5. Codeforces Round #321 (Div. 2) C Kefa and Park(深搜)

    dfs一遍,维护当前连续遇到的喵的数量,然后剪枝,每个统计孩子数量判断是不是叶子结点. #include<bits/stdc++.h> using namespace std; ; int ...

  6. ACM博弈论基础

    博弈论的题目有如下特点: 有两名选手 两名选手交替操作,每次一步,每步都在有限的合法集合中选取一种进行 在任何情况下,合法操作只取决于情况本身,与选手无关 游戏败北的条件为:当某位选手需要进行操作时, ...

  7. python基础一 day15 内置函数

    '\r' 回车,回到当前行的行首,而不会换到下一行,如果接着输出的话,本行以前的内容会被逐一覆盖: '\n' 换行,换到当前位置的下一行,而不会回到行首: # print()# input()# le ...

  8. 超全面Java 面试题(2.1)

    这部分主要是开源JavaEE框架方面的内容,包括hibernate.MyBatis.spring.Spring MVC等,由于Struts2已经是明日黄花,在这里就不讨论Struts2的面试题,此外, ...

  9. targetcli save error

    iscsi configuration unable to save python error “ValueError: 'Implict and Explict' is not in list” / ...

  10. bootstrap 超大屏幕(Jumbotron)

    本章将讲解Bootstrap的一个特性:超大屏幕(Jumbonron),顾名思义该组件可以增加标题的大小,并为登录页面的内容添加更多的外边矩. 使用超大屏幕的步骤如下: 1.创建一个还有class.j ...