Example code for MVC pattern usage in PHP

Source: Internet
Author: User
The MVC pattern is the abbreviation for "Model-view-controller", and the Chinese translates to "mode-view-controller". MVC applications are always made up of these three parts. Event causes the controller to change the model or view, or to change both. As long as the controller changes the data or attributes of the models, all dependent view will be updated automatically. Similarly, as long as the controller changes the View,view will retrieve the data from the potential model to refresh itself. The MVC pattern was first proposed by the Smalltalk language research group and applied to user interaction applications. There are many similarities between the Smalltalk language and the Java language, both object-oriented languages, and it is natural for sun to recommend the MVC pattern as an architectural model for developing Web applications in the Petstore (pet store) case application. The MVC pattern is an architectural pattern that requires other modes of collaboration to complete. In the Java EE Pattern directory, the service to worker pattern is typically implemented, and the service to worker mode can be composed of a centralized controller mode, a dispatcher mode, and a page helper mode. Struts only implemented the MVC view and controller two parts, the model part needs to be implemented by the developers themselves, Struts provides an abstract class action that enables developers to apply model to the Struts framework where model is part of the component state and low-level behavior that manages its own state and handles all operations on the state. Model itself does not know who to use its own view and controller, the system maintains its relationship with the view, when the model has changed the system is also responsible for notifying the corresponding view.

View represents a visual representation of the data contained in the management model. A model can have more than one view, but this is rarely the case in swing.

The controller manages the control of the interaction between the model and the user. It provides some ways to deal with situations where the state of the model has changed.

Application of MVC pattern in PHP
First, let me give you an example:
A simple article display system
During the simple period, we assume that the article system is read-only, which means that this example will not involve the publication of the article, and now begins.
I have defined two interface because it involves only the read of a database

Interface dataoperation {public    function Select ($info);    Public Function Selectnum ($info); }

Above this interface defines the interface to read the data, and the Select method returns the desired article. The Selectnum method returns the total number of articles, which is used when pagination is displayed. $info is an array that is used to store query conditions

Interface DataSource {public    static function getinstance ();}

Here we assume that we operate the database, DataSource defines an interface, and all instance classes that implement the interface will get a static object

Interface Controller {public    function pop ();    Public function push ();    Public function execute (); } Interface View {public    function display ();}

Okay, let's do this.
A class is defined below to implement the DataSource interface, which uses a singleton pattern

Class Databasesource implements DataSource {public    static $instance = null;    public static function getinstance ()    {        if (self:: $instance = = null)        {self            :: $instance = = new PDO ("MySQL : Host=localhost;dbname=article "," root "," 123456 ");        }        Return self:: $instance;    } }

Define an abstract class to implement Dataoperation, we want to share a database connection, so I initialize this database object in an abstract class so that all subclasses can share this object

Abstract class Databaseoperation implements Dataoperation {    protected $db = null;     Public function construct ()    {        $this->db = Databasesource::getinstance ();    }    Public Function Select ($info); }

Let me write a business subclass to implement abstract class Databaseoperation

Class Tech extends Databaseoperation {public    function Select ($info)    {        //implement your code here    }    Public function Selectnum ($info)    {        //implement your code here    }}

The business logic layer we implemented, here is the control layer

Class Viewcontroller implements Controller {    private $mod = Array ();    Public function push ($key, $value);    {        //implement your code, register the class in $this->mod;    }    Public function Pop ($key)    {                //implement your code, $this->mod[$key] value is null;    }    Public function Execute ($key)    {        //implement your code here, build the instance. Note the use of PHP5 new features, exception handling    }}

Okay, here's the presentation layer, which will implement Interface View

Abstract Articleview implements View {    protected $smarty = null;    Public function construct ()    {        $this->smarty = new Smarty ();        Below you can define some property values for Smarty    }}

Specific pages, such as the display page for scientific articles

Class Techarticleview extends Articleview {public    function display ()    {        //implement your code, Call the tech class and more Databaseoperation    }}

Okay, here's the total entrance index.php.

try {    $viewController = new Viewcontroller ();    $viewController->push ("Tech", techarticleview);   Continuous increase      $mod = $_get["mod"]:$_get["mod"]:$_post["mod"];    Finally    $viewController->execute ($key);} catch (Exception $e) {        //How to handle the exception is your business}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.