mvc模式 php
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!
欢迎来到这个由两部分组成的系列文章的第2部分,该系列讨论MVC和PHP,其中我们将讨论使用MVC体系结构时必须考虑的一些注意事项。 如果您直接阅读本文而没有先阅读第1部分,那么我建议您退一步并仔细阅读,因为这篇文章将假定您已经阅读并理解了本文讨论的所有内容。 考虑到这一点,让我们开始吧!
路由和URL (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.
尽管从理论上讲,MVC应该在所有形式的计算机编程中都可以正常工作,但是将MVC与PHP集成到Web上可能有些棘手。 第一个问题是URL路由。 URL路由是创建MVC时从未考虑过的一个方面,因此,随着Internet随着技术的扩展而发展和发展,我们使用的体系结构模式也必须如此。
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:
那么,我们有什么解决URL路由问题的选择呢? 一种解决方案是尝试抢占您的网站或Web应用程序所需的所有URL,将它们存储在永久存储中,以及有关为每个页面或部分加载哪个Model,View和Controller的信息。 然后,系统获取用户请求的URL,并加载为该页面分配的特定组件,然后开始工作。 如果您要创建不依赖动态URL的投资组合网站或静态网站,那么这是一个非常可行的解决方案。 例如:
<?php
$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.
示例MVC系统为请求的页面加载特定的模型,视图和控制器集。 如果URL参数是“ about”,则将显示About页面。 如果参数为“ portfolio”,则将改为“ Portfolio”页面。
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.
另一个选择是打开Model,View和Controller类的分配,并让URL定义这些参数。 在静态路由示例中,我们仅从数组中提取了类的标识,而该数组又充当了来自永久存储的路由数据。 用元素替换数组会将我们的静态路由变成动态路由。
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:
尽管事实上我们使用URL变量为数组中的每个关联拉了一个键,但与相应类的关系已经预先定义; 我们无法使用静态路由在每个键的值之间混合和匹配。 但是,为什么我们还要这么做呢? 对于初学者来说,我们不必对系统的每个部分进行硬编码。 我们可以仅通过创建模型,视图和控制器关系来创建部分或页面。 例如:
<?php
$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.
动作URL变量告诉系统执行Controller中的哪个功能。 重要的是要记住,当此函数将数据传递给模型时,它会将一条数据传递给模型,该数据又将指示要加载哪个View和View Action。 这可以是操作URL变量,但也可以是单独的变量,也可以是Controller收集的数据。 切记永远不要允许Controller加载数据或将数据直接传递给View; 它只能与模型和用户输入交互。
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.
但是,与静态路由相比,动态路由可以给Controller带来更多的责任,这可以看作是在改变传统的MVC模式。 但是,如果正确有效地实现了动态路由,则与使用静态路由相比,可以使Controller在系统内更加理想。
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.
添加前端控制器将使您的系统可以动态加载节,具体取决于您要加载的部分。 Alejandro Gervasio写了一篇由两部分组成的有关前端控制器模式的精彩文章,其中涉及将前端控制器与MVC元素一起使用的想法。 我强烈建议任何希望了解前端控制器和MVC的人使用此工具。 我还建议您快速访问Tom Butler的站点,因为他有一篇文章着眼于如何将前端控制器实现到他的“ 1.1 Controller:View”关系中,对于那些希望在其MVC系统中开发真正的动态路由解决方案的人来说是理想的选择。
干(不要重复自己)和模板 (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.
我使用MVC模式的主要论据之一是旨在使您的整个系统尽可能地井井有条。 最明显的方法是减少使用同一代码的多个实例的机会。 任何开发人员都会同意,在任何应用程序中发现的最糟糕的事情是重复相同的代码。 保持代码精简并尽可能多地使用可重用组件的做法被称为DRY理念–不要重复自己。
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.
DRY原则规定“每条知识在系统中必须具有单一,明确,权威的表示形式”。 DRY的目的是增加和探索对开发人员开放的所有可能途径,以使他们的系统尽可能地动态和优化。 DRY原理意味着,如果您需要在许多地方编写同一段代码,而不是在这些地方重复代码,请创建一个单独的方法并在需要时使用它。 这使系统变得更加优化,并引入了在我们的系统中进行缓存的可能性,以帮助改善整体运行时间。
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.
DRY的正确实现将意味着更改系统的一个元素不会更改不相关的元素,这使DRY成为使用MVC模式进行开发时必须遵循的重要原则。
范本 (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.
对于大多数以前看过MVC Web框架的人来说,“模板”一词可能会引起一些问题,因为大多数人将模板部分与View结合在一起。 如前所述,如果您希望坚持使用传统的MVC模式,这是不正确的。 理想情况下,在从Model收集数据之后,您将让View处理数据处理和处理。 因此,只有您的View组件选择模板并将数据从View传递到该模板才有意义。 这样,就可以使用块代码布局或在PHP中使用回显,打印或任何其他输出代码来显示它了。 无论选择使用哪种方法,主要要记住的是数据必须处于就绪状态,您只需要在模板中打印数据即可。 如果您正在模板中进行其他数据处理或处理,则您的设置有误,很可能是MVC设置不正确。
Here’s a quick example of your view loading a template and pushing data to it:
这是您的视图加载模板并将数据推送到其中的快速示例:
<?php
class Model
{
public $tstring;
public function __construct(){
$this->tstring = "The string has been loaded through the template.";
$this->template = "tpl/template.php";
}
}
<?php
class View
{
private $model;
public function __construct($model) {
$this->controller = $controller;
$this->model = $model;
}
public function output(){
$data = "<p>" . $this->model->tstring ."</p>";
require_once($this->model->template);
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="charset=utf-8">
<title>The Template name</title>
</head>
<body>
<h1><?php echo $data; ?></h1>
</body>
</html>
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.
此外,模板还通过模型传递,原则上可以根据每个特定View的意图动态分配模板。 这种模板化方法使MVC系统可以高效,可靠地扩展,同时使我们可以选择将后端开发与前端开发分开; MVC模式的原始目标。
结论 (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模式首次用于桌面编程时,它就改变了游戏规则。 在使用它进行开发时,关于如何解释某些情况,这一直是并且仍然是开发人员之间争论不休的话题。 当您将PHP和Web添加到组合中时,辩论变得更加激烈,这是一个奇妙的信号,表明越来越多的开发人员开始专注于改进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.
MVC之所以受到个人欢迎,是因为它鼓励不同处理部分之间的分离,以及前端与后端之间分离的机会。 我恳求那些以前从未使用MVC开发的人(尤其是在PHP中),将他们的牙齿投入这一奇妙的开发模式中。 你不会失望的。
Comments on this article are closed. Have a question about MVC Patterns and PHP? Why not ask it on our forums?
本文的评论已关闭。 对MVC模式和PHP有疑问吗? 为什么不在我们的论坛上提问呢?
Image via Fotolia
图片来自Fotolia
mvc模式 php