MVC pattern application skills sample code in php
MVC pattern is the abbreviation of "Model-View-Controller", and the Chinese translation is "Model-View-Controller". MVC applications always consist of these three parts. Event (event) causes the Controller to change the Model or View, or both at the same time. As long as the Controller changes the data or properties of the Models, all dependent Views will be automatically updated. Similarly, whenever the Controller changes the View, the View will refresh itself by getting data from the underlying Model. The MVC pattern was first proposed by the Smalltalk language research group and is used in user interaction applications. There are many similarities between the smalltalk language and the java language. They are both object-oriented languages. Naturally, SUN recommended the MVC pattern as the architectural pattern for developing Web applications in the petstore (pet store) example application. The MVC pattern is an architectural pattern that actually requires the collaboration of other patterns. In the J2EE mode directory, service to worker mode is usually implemented, and service to worker mode can be composed of centralized controller mode, dispatcher mode and Page Helper mode. Struts only implements the View and Controller parts of MVC. The Model part needs to be implemented by developers themselves. Struts provides the abstract class Action so that developers can apply Model to the Struts framework. Model is the part that represents component status and low-level behavior. , it manages its own state and handles all operations on the state. The model itself does not know who is using its own view and controller. The system maintains the relationship between it and the view. When the model changes, 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 methods to handle situations when the model's state changes.
Using the MVC pattern in php
A simple
Article display
SystemIn a simple period, we assume that this article system is only Reading, which means that this example will not involve the publication of the article, starts now. Since it only involves database reading, I defined two interfaces
Interface DataOperation { public function select($info); public function selectNum($info); }
The above interface defines the interface for reading data, select method
will return all Articles needed. The selectNum method returns the total number of articles, which is used for paging display. $info is an array used to store query conditions
Interface DataSource { public static function getInstance(); }
Here we assume that we are operating a database, DataSource defines an interface, and all instance classes that implement this 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 implement it. The following defines a class to implement the DataSource interface. This class uses the
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; } }
Definition An Abstract class
to implement DataOperation, we need to share a database connection, so I initialize the database object in the 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); }
Next I will write a business subclass to implement the abstract class DataBaseOperation
class Tech extends DataBaseOperation { public function select($info) { //在这里实现你的代码 } public function selectNum($info) { //在这里实现你的代码 } }
We have implemented the business logic layer, and the following is the control layer
class ViewController implements Controller { private $mod = array(); public function push($key,$value); { //实现你的代码,将类注册进$this->mod; } public function pop($key) { //实现你的代码,将$this->mod[$key]值为null; } public function execute($key) { //在这里实现你的代码,生成实例.注意利用php5新的特性,异常的处理 } }
Okay, here is the presentation layer, where the Interface View
abstract ArticleView implements View { protected $smarty = null; public function construct() { $this->smarty = new Smarty(); ///下面你可以定义smarty的一些属性值 } }
will be implemented. Specific pages, such as the display page of scientific and technological articles
class TechArticleView extends ArticleView { public function display() { //实现你的代码,调用Tech类和更多的DataBaseOperation子类 } }
Okay, here is the general entrance. index.php
try { $viewController = new ViewController(); $viewController->push("tech",TechArticleView); //持续的增加 $mod = $_GET["mod"]:$_GET["mod"]:$_POST["mod"]; //最后 $viewController->execute($key); } catch( Exception $e) { //如何处理异常就是你的事了 }
The above is the detailed content of MVC pattern application skills sample code in php. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
