search
HomeBackend DevelopmentPHP TutorialMVC pattern application skills sample code in php

MVC pattern application skills sample code in php

Jul 12, 2017 pm 02:28 PM
phpSkillExample

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

First of all, let me give an example:

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

single case mode

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

How often should you regenerate session IDs?How often should you regenerate session IDs?Apr 23, 2025 am 12:03 AM

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version