」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > PHP主| MVC模式和PHP,第2部分

PHP主| MVC模式和PHP,第2部分

發佈於2025-03-24
瀏覽:525

PHP主| MVC模式和PHP,第2部分

Welcome to part 2 of this two-part series discussing MVC and PHP, where we’ll discuss some of the considerations one must make when using an MVC architecture. If you’ve come straight to this article without reading part 1 first, I encourage you to head back and have careful read as this one will assume that you’ve read and understand everything it discussed. With that in mind, let’s get started!

Key Takeaways

  • MVC (Model-View-Controller) pattern, while theoretically perfect for all computer programming, can present challenges when incorporated into PHP for web use, particularly in terms of URL routing.
  • A possible solution to the URL routing issue involves preempting necessary URLs and storing them with corresponding Model, View, and Controller information. This method, known as static routing, is suitable for static websites but may limit scalability.
  • An alternate approach, dynamic routing, lets the URL define the Model, View, and Controller classes. This approach allows for greater scalability and portability, but places more responsibility on the Controller, potentially altering the traditional MVC pattern.
  • Adherence to the DRY (Don’t Repeat Yourself) principle, which discourages code repetition, can help optimize the system. Correct implementation of DRY in MVC patterns ensures that changing one system element does not affect unrelated elements.

Routing and URLs

Although MVC, in theory, should work flawlessly in all forms of computer programming, incorporating MVC on the web with PHP can be a bit tricky. The first problem is with URL routing. URL routing is an aspect that was never considered when MVC was created, and so as the Internet evolves and develops with the expansion of technology, so must the architecture patterns we use. So what options do we have for solving the URL routing problem? One solution is to attempt to preempt any URLs that your site or web app needs, storing them in permanent storage along with information about which Model, View, and Controller to load for each page or section. The system then gets the URL requested by the user and loads the specific components assigned for that page and gets to work. This is a perfectly feasible solution if you are creating a portfolio site or a static website, which doesn’t rely on dynamic URLs. For example:
$page = $_GET['page'];
if (!empty($page)) {

    $data = array(
        'about' => array('model' => 'AboutModel', 'view' => 'AboutView', 'controller' => 'AboutController'),
        'portfolio' => array('model' => 'PortfolioModel', 'view' => 'PortfolioView', 'controller' => 'PortfolioController')
    );

    foreach($data as $key => $components){
        if ($page == $key) {
            $model = $components['model'];
            $view = $components['view'];
            $controller = $components['controller'];
            break;
        }
    }

    if (isset($model)) {
        $m = new $model();
        $c = new $controller($model);
        $v = new $view($model);
        echo $v->output();
    }
}
Our URLs would look like this:
example.com/index.php?page=about
or
example.com/index.php?page=portfolio
The example MVC system loads the specific Model, View, and Controller set for the requested page. If the URL parameter is “about”, then the About page will be displayed. If the parameter is “portfolio”, the Portfolio page will be instead. The is a basic example of static routing which, even through it’s very simple to set up, comes with some drawbacks. One of the most obvious drawbacks is the fact that scalability becomes much harder, as the breadth of your site is constricted to the hard-coded array of pages. Another option is to open up the assignment of your Model, View, and Controller classes and let the URL define these parameters. In the static routing example, we simply pulled the class’ identification from an array, which in turn acted as routing data coming from our permanent storage. Replacing the array with elements turns our static routing into dynamic routing. Despite the fact we pulled a key for each association in the array with a URL variable, the relationships with corresponding classes were already predefined; we couldn’t mix and match between the values in each key with static routing. But why would we even want to do this? Well for starters, we wouldn’t have to hard code each section of our system. We can create sections or pages just through creating a Model, View and Controller relationship. For example:
$model = $_GET['model'];
$view = $_GET['view'];
$controller = $_GET['controller'];
$action = $_GET['action'];

if (!(empty($model) || empty($view) || empty($controller) || empty($action))) {
    $m = new $model();
    $c = new $controller($m, $action);
    $v = new $view($m);
    echo $v->output();
}
Our new URL would now look like:
example.com/index.php?controller=controllername↦model=modelname&view=viewname&action=actionname
The action URL variable tells the system which function in the Controller to execute. It is important to remember that when this function passes data to the Model, it passes a piece of data to the Model that will in turn indicate which View and View Action to load. This can be the action URL variable, but it can also be separate, or data collected by the Controller. Remember to never allow the Controller to load or directly pass data to the View; it must only interact with the Model and the User’s inputs. Both approaches have their pros and cons, with static routing being more stable, quicker to implement, and allowing developers more control over the system, and with dynamic routing allowing us to create a more effective system where there is huge potential for scalability and portability. Dynamic routing can, however, place more responsibility on the Controller than static routing, which can be seen as altering the traditional MVC pattern. Nevertheless, if dynamic routing is implemented correctly and effectively, is can make the Controller more desirable within the system compared to using static routing. Adding a Front Controller will allow your system to dynamically load sections, depending on what you want it to load. Alejandro Gervasio has written a fantastic 2-part article about the Front Controller pattern, which touches on ideas of using a Front Controller with elements of MVC. I highly recommend this for anyone wishing to know more about Front Controllers and MVC. I also recommend a quick visit to Tom Butler’s site as he has an article which looks at implementing the Front Controller into his “1.1 Controller:View” relationship, ideal for those looking to develop a true dynamic routing solution into their MVC system.

DRY (Don’t Repeat Yourself) & Templates

One of my main arguments for using the MVC pattern is the aim to make your overall system as organized as possible. The most obvious way to do this is to reduce the amount of opportunities to have multiple instances of the same code. Any developer will agree that the worst thing to find in any application is repetition of the same code. The practice of keeping your code streamlined and using reusable components as much as possible is know as the DRY philosophy – Don’t Repeat Yourself. The DRY principle dictates that “every piece of knowledge must have a single, unambiguous, authoritative representation within a system.” The aim of DRY is to increase and explore every possible avenue open to developers to make their system as dynamic and optimized as possible. DRY principle implies that, if you need to write the same piece of code in many places, instead of repeating the code at these places, create a separate method and use it wherever required. This allows the system to become more optimized and introduces the possibility of caching within our systems to help improve the overall run time. A correct implementation of DRY would imply that changing one element of the system does not change unrelated elements, which makes DRY an important principle to work to when developing with MVC patterns.

Templates

The word “template” might raise a few questions for those who have seen MVC web frameworks before, as most people lump the template part in with the View. As we’ve discussed before, this is incorrect if you wish to stick with the traditional MVC pattern. Ideally, you would have the View dealing with the data crunching and processing after collecting the data from the Model. Therefore it only makes sense for your View component to select a template and pass the data from the View into that template. That way it is ready to be displayed using a block code layout, or with an echo, print, or any other outputting code in PHP. Whichever of those methods you choose to use, the main thing to remember is that your data MUST be at a state of readiness that you only need to print the data in the template. If you are doing other data processing or crunching in the template your setup is wrong, and most likely, the MVC setup is incorrect. Here’s a quick example of your view loading a template and pushing data to it:
class Model
{
    public $tstring;

    public function __construct(){
        $this->tstring = "The string has been loaded through the template.";
        $this->template = "tpl/template.php";
    }
}
class View
{
    private $model;

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

    public function output(){
        $data = "

" . $this->model->tstring ."

";
require_once($this->model->template); } }

>
 >
   charset="charset=utf-8">
  >The Template name>
 >
 >
  

>

>
> >
In addition the template is being passed through the model, which in principle can allow for dynamic assignment of templates depending on what each particular View is meant to be doing. This method of templating allows MVC systems to be expanded upon efficiently and confidently, while giving us the option to split the back end development from the front end development; an original goal of the MVC pattern.

Conclusion

The MVC pattern was a game changer when it was first used for desktop programming. It was, and still is, a highly debated topic between developers with regard to interpreting certain scenarios when developing with it. The debate becomes even more intense when you add PHP and the web into the mix, which is a fantastic sign that more and more developers are becoming focused on improving development disciplines for PHP. MVC is a personal favorite because of its encouragement of separation between the different processing parts, and the opportunity of separation between the front end and the back end. I implore anyone who hasn’t developed with MVC before, especially in PHP, to sink their teeth into this wonderful development pattern; you will not be disappointed. Comments on this article are closed. Have a question about MVC Patterns and PHP? Why not ask it on our forums? Image via Fotolia

Frequently Asked Questions about MVC Pattern and PHP

What is the MVC pattern and why is it important in PHP?

The Model-View-Controller (MVC) pattern is a design pattern that separates an application into three interconnected components. This separation allows for efficient code organization, making it easier to manage and maintain. In PHP, the MVC pattern is crucial as it helps in building scalable and robust applications. It allows developers to change the interface without affecting the business logic and vice versa, promoting a more efficient development process.

How does routing work in a PHP MVC application?

Routing in a PHP MVC application is the process of taking a URL and deciding which controller and action to call. It’s like a map for your application, directing the flow of data and ensuring that requests are sent to the correct place. This is typically handled by a router class, which parses the URL and determines the appropriate controller and method to invoke.

How can I create a simple MVC framework with PHP routing?

Creating a simple MVC framework with PHP routing involves several steps. First, you need to set up the basic file structure for your MVC application. Then, you need to create a router class that will handle the routing logic. This class will parse the URL and determine which controller and method to call. After that, you need to create the controllers and models for your application. Finally, you need to set up your views, which will display the data to the user.

What are some common challenges when implementing MVC in PHP and how can they be overcome?

Some common challenges when implementing MVC in PHP include understanding the separation of concerns, managing data flow, and setting up routing. These challenges can be overcome by thoroughly understanding the MVC pattern and its principles, planning your application structure carefully, and using a routing library or creating a custom router to handle the routing logic.

Can you provide a practical example of PHP MVC routing?

Yes, a practical example of PHP MVC routing would involve a URL like “www.example.com/products/edit/1”. In this case, the router would parse the URL and determine that it needs to call the “edit” method of the “products” controller, passing “1” as a parameter. This would result in the application displaying the edit page for the product with an ID of 1.

How does the MVC pattern affect the performance of a PHP application?

The MVC pattern can greatly improve the performance of a PHP application. By separating the application into three components, it allows for more efficient code organization and management. This can result in faster response times and a better user experience.

What are the benefits of using MVC pattern in PHP?

The MVC pattern offers several benefits when used in PHP. It promotes code organization, making it easier to manage and maintain. It also allows for separation of concerns, meaning that changes to the interface won’t affect the business logic and vice versa. This can result in a more efficient development process and a more robust application.

How can I implement a simple routing system in a PHP MVC application?

Implementing a simple routing system in a PHP MVC application involves creating a router class that will handle the routing logic. This class will parse the URL and determine which controller and method to call. You can use a routing library to simplify this process, or you can create your own custom router if you prefer.

What is the role of the controller in a PHP MVC application?

The controller in a PHP MVC application acts as an intermediary between the model and the view. It handles user input, interacts with the model to retrieve or update data, and sends data to the view to be displayed to the user.

How can I improve my understanding of the MVC pattern in PHP?

Improving your understanding of the MVC pattern in PHP can be achieved through a combination of study and practice. There are many resources available online, including tutorials, articles, and videos, that can help you learn more about this design pattern. Additionally, building your own MVC application can provide valuable hands-on experience.

最新教學 更多>
  • 表單刷新後如何防止重複提交?
    表單刷新後如何防止重複提交?
    在Web開發中預防重複提交 在表格提交後刷新頁面時,遇到重複提交的問題是常見的。要解決這個問題,請考慮以下方法: 想像一下具有這樣的代碼段,看起來像這樣的代碼段:)){ //數據庫操作... 迴聲“操作完成”; 死(); } ? > ...
    程式設計 發佈於2025-05-09
  • 如何簡化PHP中的JSON解析以獲取多維陣列?
    如何簡化PHP中的JSON解析以獲取多維陣列?
    php 試圖在PHP中解析JSON數據的JSON可能具有挑戰性,尤其是在處理多維數組時。 To simplify the process, it's recommended to parse the JSON as an array rather than an object.To do...
    程式設計 發佈於2025-05-09
  • 編譯器報錯“usr/bin/ld: cannot find -l”解決方法
    編譯器報錯“usr/bin/ld: cannot find -l”解決方法
    錯誤:“ usr/bin/ld:找不到-l “ 此錯誤表明鏈接器在鏈接您的可執行文件時無法找到指定的庫。為了解決此問題,我們將深入研究如何指定庫路徑並將鏈接引導到正確位置的詳細信息。 添加庫搜索路徑的一個可能的原因是,此錯誤是您的makefile中缺少庫搜索路徑。要解決它,您可以在鏈接器命令中添...
    程式設計 發佈於2025-05-09
  • 如何使用Regex在PHP中有效地提取括號內的文本
    如何使用Regex在PHP中有效地提取括號內的文本
    php:在括號內提取文本在處理括號內的文本時,找到最有效的解決方案是必不可少的。一種方法是利用PHP的字符串操作函數,如下所示: 作為替代 $ text ='忽略除此之外的一切(text)'; preg_match('#((。 &&& [Regex使用模式來搜索特...
    程式設計 發佈於2025-05-09
  • Java中如何使用觀察者模式實現自定義事件?
    Java中如何使用觀察者模式實現自定義事件?
    在Java 中創建自定義事件的自定義事件在許多編程場景中都是無關緊要的,使組件能夠基於特定的觸發器相互通信。本文旨在解決以下內容:問題語句我們如何在Java中實現自定義事件以促進基於特定事件的對象之間的交互,定義了管理訂閱者的類界面。 以下代碼片段演示瞭如何使用觀察者模式創建自定義事件: args...
    程式設計 發佈於2025-05-09
  • 在Ubuntu/linux上安裝mysql-python時,如何修復\“ mysql_config \”錯誤?
    在Ubuntu/linux上安裝mysql-python時,如何修復\“ mysql_config \”錯誤?
    mysql-python安裝錯誤:“ mysql_config找不到”“ 由於缺少MySQL開發庫而出現此錯誤。解決此問題,建議在Ubuntu上使用該分發的存儲庫。使用以下命令安裝Python-MysqldB: sudo apt-get安裝python-mysqldb sudo pip in...
    程式設計 發佈於2025-05-09
  • eval()vs. ast.literal_eval():對於用戶輸入,哪個Python函數更安全?
    eval()vs. ast.literal_eval():對於用戶輸入,哪個Python函數更安全?
    稱量()和ast.literal_eval()中的Python Security 在使用用戶輸入時,必須優先確保安全性。強大的Python功能Eval()通常是作為潛在解決方案而出現的,但擔心其潛在風險。 This article delves into the differences betwee...
    程式設計 發佈於2025-05-09
  • Spark DataFrame添加常量列的妙招
    Spark DataFrame添加常量列的妙招
    在Spark Dataframe ,將常數列添加到Spark DataFrame,該列具有適用於所有行的任意值的Spark DataFrame,可以通過多種方式實現。使用文字值(SPARK 1.3)在嘗試提供直接值時,用於此問題時,旨在為此目的的column方法可能會導致錯誤。 df.withco...
    程式設計 發佈於2025-05-09
  • Go web應用何時關閉數據庫連接?
    Go web應用何時關閉數據庫連接?
    在GO Web Applications中管理數據庫連接很少,考慮以下簡化的web應用程序代碼:出現的問題:何時應在DB連接上調用Close()方法? ,該特定方案將自動關閉程序時,該程序將在EXITS EXITS EXITS出現時自動關閉。但是,其他考慮因素可能保證手動處理。 選項1:隱式關閉終...
    程式設計 發佈於2025-05-09
  • 如何將PANDAS DataFrame列轉換為DateTime格式並按日期過濾?
    如何將PANDAS DataFrame列轉換為DateTime格式並按日期過濾?
    Transform Pandas DataFrame Column to DateTime FormatScenario:Data within a Pandas DataFrame often exists in various formats, including strings.使用時間數據時...
    程式設計 發佈於2025-05-09
  • 為什麼HTML無法打印頁碼及解決方案
    為什麼HTML無法打印頁碼及解決方案
    無法在html頁面上打印頁碼? @page規則在@Media內部和外部都無濟於事。 HTML:Customization:@page { margin: 10%; @top-center { font-family: sans-serif; font-weight: ...
    程式設計 發佈於2025-05-09
  • 如何為PostgreSQL中的每個唯一標識符有效地檢索最後一行?
    如何為PostgreSQL中的每個唯一標識符有效地檢索最後一行?
    postgresql:為每個唯一標識符在postgresql中提取最後一行,您可能需要遇到與數據集合中每個不同標識的信息相關的信息。考慮以下數據:[ 1 2014-02-01 kjkj 在數據集中的每個唯一ID中檢索最後一行的信息,您可以在操作員上使用Postgres的有效效率: id dat...
    程式設計 發佈於2025-05-09
  • 如何從PHP中的Unicode字符串中有效地產生對URL友好的sl。
    如何從PHP中的Unicode字符串中有效地產生對URL友好的sl。
    為有效的slug生成首先,該函數用指定的分隔符替換所有非字母或數字字符。此步驟可確保slug遵守URL慣例。隨後,它採用ICONV函數將文本簡化為us-ascii兼容格式,從而允許更廣泛的字符集合兼容性。 接下來,該函數使用正則表達式刪除了不需要的字符,例如特殊字符和空格。此步驟可確保slug僅包...
    程式設計 發佈於2025-05-09
  • 如何修復\“常規錯誤:2006 MySQL Server在插入數據時已經消失\”?
    如何修復\“常規錯誤:2006 MySQL Server在插入數據時已經消失\”?
    How to Resolve "General error: 2006 MySQL server has gone away" While Inserting RecordsIntroduction:Inserting data into a MySQL database can...
    程式設計 發佈於2025-05-09
  • Python中何時用"try"而非"if"檢測變量值?
    Python中何時用"try"而非"if"檢測變量值?
    使用“ try“ vs.” if”來測試python 在python中的變量值,在某些情況下,您可能需要在處理之前檢查變量是否具有值。在使用“如果”或“ try”構建體之間決定。 “ if” constructs result = function() 如果結果: 對於結果: ...
    程式設計 發佈於2025-05-09

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3