PHP MVC:我真的需要一个控制器吗?

我的问题很简单,但(我猜)很难回答:</ p>

我真的需要在我的PHP网站/ Web应用程序中使用完整的模型 - 视图 - 控制器设计模式吗?</ p>

我无法理解控制器如何对PHP有用,因为每个PHP站点都是如此 是在每个请求上动态生成的。 因此,在PHP生成站点之后,无法让View(生成的HTML站点在浏览器中)与控制器交互,因为Controller位于服务器端并为每个站点请求生成一次,即使 请求是AJAX ... </ p>

我是否理解完全错误?</ p>

为什么我应该使用任何类型的MVC PHP框架,如Zend或Symphony? </ p>

编辑:
例如假设,应该有一个网站来表示表格中的客户列表:</ p>

我的模型将是一个 查询数据库的服务器端的简单类客户。
我将查看生成的HTML代码,显示模型(客户列表)。
和控制器? 控制器是仅评估GET或POST来调用模型的正确方法吗?</ p>
</ div>

展开原文

原文

My question is simple but (I guess) hard to answer:

Do I really need a complete Model-View-Controller design pattern in my PHP Website / Web-App?

I can't understand how a Controller could be useful with PHP since every PHP site is generated dynamically on every request. So after a site is generated by PHP, there is no way to let the View (the generated HTML site in the Browser) interact with the controller, since the Controller is on the server side and generated once for each site request, even if the request is AJAX...

Do I understand something completely wrong?

Why should I use any kind of MVC PHP Framework like Zend or Symphony?

EDIT: For example lets assume, there should be a website to represent a list of customers in a table:

My Model would be a simple Class Customer on the server side that queries the database. My View would be the generated HTML code that displays the Model (list of Customers). And the controller? Is the controller only evaluating the GET or POST to call the correct method of the model?

donpvtzuux37724
donpvtzuux37724 你这么认为吗?到底是什么?
7 年多之前 回复
dongshuxi3105
dongshuxi3105 所有的“长期答案”,因为它都是错的
7 年多之前 回复
douning5041
douning5041 什么会改变,删除或添加Scotts的答案?
7 年多之前 回复
dousong4777
dousong4777 ,你选择了基于长度的“正确答案”吗?因为现在的(来自ScottBailey)是完全错误的。
7 年多之前 回复
dongwei1895
dongwei1895 它被称为模型视图控制器(MVC)。根据定义,这意味着您需要一个控制器。
接近 9 年之前 回复

3个回答

Short Answer

Yes. A controller will be responsible for preparing data to display for rendering and sometimes handle GET and POST requests that originating from your client. It should leave HTML generation to the view.

Long Answer

MVC can be very helpful in keeping applications maintainable and your code base sane. The pattern helps ensure separation of concerns of your code and in most cases will steer yor clear of 'spaghetti php' where your application logic is tangled with the HTML generation. A sample MVC setup below (there are sure to be many variations of this, but it gives you the idea):

Model

Responsible for fetching data from the database and saving changes when requested. One example might be a php object that represents a user with name and email fields.

Controller

Responsible for massaging and manipulating data and preparing it for display. The prepared data is passed to a view for rendering, with the view only needing to be aware of just the data it needs to render. For example: a controller may look at a query string to determine what item to fetch to render and combine this with several additional model queries to get additional data.

Often controllers will also be responsible for handling GET and POST requests that originate from your HTML client and applying some sort of manipulation back on your database. For example - handling form submits or AJAX requests for additional data.

View

The view is responsible for actually generating the HTML for display. In PHP, a view would often be a template file with minimal logic. For example, it might know how to loop over items provided to it from the controller or have some basic conditionals.

Application MVC vs PHP/Python/etc. MVC

From your other comments it sounds like you are familiar with using MVC in the context of a desktop or mobile application.

One of the main differences between MVC in the two is the granularity at which the controller is manipulating the view and responding to events.

For example, in a traditional application the controller might listen for click events originating from a button and respond appropriately.

When your doing server side html generation however, your controller is only 'alive' for a brief moment while its preparing html to ship out over the wire. This means that it can only do so much to setup and prepare the view for display.

Instead of listening traditional events from the UI, it can instead react in different ways to future GET and POST requests. For example, you may have a "save" button on a form trigger a POST request to your server (such as yourpage.php?action=save&value=blah). While handling this request your controller might access your models and apply changes, etc.




我是否理解完全错误?</ p>
</ blockquote>

< p>是的。 </ p>

MVC模式不适用于浏览器。 浏览器无论如何都会看到HTML。 是否使用C ++,PHP,Java或其他任何内容生成此HTML。 浏览器不关心用于生成此HTML的设计模式。 </ p>

MVC是一种设计模式,用于组织和分离代码中的职责。 所以不是浏览器,而是开发人员编写代码。 这是为了创建更易于维护的代码,您可以在业务逻辑(模型),模型与视图(Controller)和UI(视图)之间的通信之间进行明确分离。</ p>

是否 你应该在你的网站上使用MVC模式是一个主观问题,我不想回答,因为它取决于很多因素。</ p>
</ div>

展开原文

原文

Do I have understand something completely wrong?

Yes.

The MVC pattern is not for the browser. The browser sees HTML anyways. Whether this HTML is generated with C++, PHP, Java or whatever it doesn't matter. The browser doesn't care what design patterns were used to generate this HTML.

MVC is a design pattern to organize and separate responsibilities in your code. So it's not for the browser, it's for the developers writing the code. It's to create more maintainable code where you have a clear separation between your business logic (Model), the communication between the model and the view (Controller) and the UI (View).

Whether you should use the MVC pattern in your web site is a subjective question that I prefer not to answer as it will depend on many factors.

drmticpet66231422
drmticpet66231422 是的,谢谢你加入! 从我的角度来看,名称只是问题(至少如果你是桌面应用程序开发人员),因为网络应用程序中的MVP与桌面应用程序中的MVP不同,它们是两个不同的东西(就像你说的那样)。
大约 6 年之前 回复
dongyongyin5339
dongyongyin5339 是的,你是对的,因为这是MVC的成果。 你正在做的是普通的做法,并被广大社区广泛接受,控制者充当调解员/中间人。 我想在这里添加的是,用于网络的MVC已经变异为不再是MVC的观点。 我相信你个人会克服这个特殊问题,但是,我认为你回到那里的其他人可能会从另一种观点中找到一些用途。
大约 6 年之前 回复
duandongjin5647
duandongjin5647 现在3年后,我明白了如何将MVC用于网络应用程序。 关键是,桌面应用程序的MVC与Web应用程序的MVC不同。 在桌面MVC应用程序中,控制器将对GUI事件做出反应并操纵模型。 在MVC for web apps中,您的控制器是切入点。 在这里,您将开始处理您的http请求并操纵或获取模型并将其提供给视图(将模型表示为html,json)。 所以它是某种中间人。 对我来说,如果你想将它与桌面进行比较,它看起来更像是Model-View-Presenter Passive View
大约 6 年之前 回复
dsfs64664
dsfs64664 仍然需要PHP应用程序中的Controller,但是您只需要一个Controller来处理旨在操纵特定Model的请求。 您不需要Controller即可显示某些数据。 根据MVC原则,View可以直接访问它的模型。
大约 6 年之前 回复
dongshanjin8947
dongshanjin8947 同意它是“组织和分离责任”,但是大多数PHP MVC应用程序给Controller的责任是不正确的。 Controller仍然负责根据用户请求操作Model,它不负责提取数据并将其传递给View。
大约 6 年之前 回复
dtddjq9637
dtddjq9637 是的,我完全赞同你和他,MVC是你应该经常使用的模式! 但我无法在PHP中看到Controller的责任。 有人能给我一个PHP控制器的例子吗? 顺序图(文本形式)将有助于=)
接近 9 年之前 回复
dongpiao0731
dongpiao0731 你是正确的,因为PHP应用程序的MVC与(例如)持久桌面应用程序中的MVC不同。 但这并不意味着控制器无用。 我认为达​​林答案的关键点在于它允许你“组织和分离责任”。
接近 9 年之前 回复
duancao1951
duancao1951 我的意思是,在一个经典的Java应用程序中,我会有一个Controller,它可以监听View的某些输入(比如点击一个按钮),然后Controller会让Model执行某些操作......但是在Web应用程序中, 我会点击一个按钮,然后会有东西被发送到服务器,然后我将被重定向到一个新的站点(一个新的视图),它显示一些东西,这取决于按钮点击...但我看不到一个 控制器在这种情况下
接近 9 年之前 回复
douyanjing8287
douyanjing8287 谢谢您的回答。 我编辑我之前的帖子(添加了一个小例子),如果你看看这个例子会很好。 我知道MVC模式,我理解MVC模式是如何工作的以及它的优点(至少在经典桌面应用程序中),但我不明白如何在PHP中实现控制器? 我的意思是,在每次请求时都会使用PHP生成一个站点,因此在我看来,HTTP本身就是Web应用程序中的控制器......
接近 9 年之前 回复

I realise that I am answering a very old questions, however, I do not believe that any other question has answered your initial concern appropriately, and this will hopefully add something useful for others who may stumble across this question in their learning about MVC.

Firstly, I will start by saying I read an interesting article about the confusion which exists within the PHP community about MVC and it is worth a read if you are asking this type of question.

Model-View-Confusion part 1: The View gets its own data from the Model

Secondly, I do not believe you have misunderstood anything at all, rather you have a better understanding of PHP and MVC which is allowing you to ask the question. Just because something has been defined and accepted by the community at large, it does not mean you should't question its use from time to time. And here is why.

There is NO memory between requests (except for SESSION state) within a PHP application. Every time a request is received the entire application fires up, processes the request and then shuts down i.e. there are no background application threads left running in the background (at least none which you can use within your application) where you could, theoretically, maintain application state. This is neither good, nor bad, it is just the way it is.

Understanding this, you can probably start to see what you are thinking is correct. Why would a View (which is allowed to access its own data from the Model) need a Controller? The simple answer, is that it doesn't. So for the pure display of a Model, the View is perfectly entitled to fetch its own data (via the Model) and it is actually the correct way to implement MVC.

But wait. Does this mean we don't need Controllers? Absolutely NOT! What we need to do is use a Controller for its appropriate purpose. In MVC, the Controller is responsible for interpreting user requests and asking the Model to change itself to meet the users request, following this, the Model can notify it's dependencies of the change and the View can update itself. Obviously, as you know, in the context of a PHP web application, the View is not just sitting and waiting for update notifications. So how can you achieve the notification?

This is where I believe MVC got hijacked. To notify the View it's Model has changed, we can simply direct them to the URL of the View which accesses the now updated Model. Great, but now we have introduced something into the Controller. Something which says, "Hey, I'm a controller but now I have knowledge of the location of the View." I think at this point, someone thought, "why do I bother redirecting the user? I have all the data which the View needs why don't I just send the data directly to the View?" and bang! Here we are.

So let's recap.

  1. A View CAN access the Model directly within MVC
  2. The Model houses the business logic for the Domain Objects
  3. A Controller is not meant to provide the View access to the Model or act as any type of mediator
  4. The Controller accepts user requests and makes changes to it's Model
  5. A View is not the UI/HTML, that is where a Template is used

A practical example To explain what I have been describing, we shall look at a simple, commonly found function within most websites today. Viewing the information of a single logged in user. We will leave many things out of our code here in order to demonstrate just the structure of the MVC approach.

Firstly lets assume we have a system where when we make a GET request for /user/51 it is mapped to our UserView with the appropriate dependencies being injected.

Lets define our classes.

// UserModel.php
class UserModel {
    private $db;

    public function __construct(DB $db) {
        $this->db = $db;
    }

    public function findById($id) {
        return $this->db->findById("user", $id);
    }
}

// UserView.php
class UserView {
    private $model;
    private $template;
    private $userId;

    public function __construct(UserModel $model, Template $template) {
        $this->model = $model;
        $this->template = $template;
    }

    public function setUserId($userId) {
        $this->userId = $userId;
    }

    public function render() {
        $this->template->provide("user", $this->model->findById($this->userId));
        return $this->template->render();
    }
}

And that's it! You do not require the Controller at all. If however you need to make changes to the Model, you would do so via a Controller. This is MVC.

Disclaimer

I do not advocate that this approach is correct and any approach taken by any developer at any point in time is wrong. I strongly believe that the architecture of any system should reflect its needs and not any one particular style or approach where necessary. All I am trying to explain is that within MVC, a View is actually allowed to directly access it's own data, and the purpose of a Controller is not to mediate between View and Model, rather it is intended to accept user requests which require manipulation of a particular Model and to request the Model to perform such operations.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐