如何在 MVC 的 PHP 页面之间传递值?

发布于 2024-09-25 18:21:17 字数 157 浏览 4 评论 0原文

PHP 程序如何在模型、视图和控制器页面之间传递值?例如,如果控制器有一个数组,它如何将其传递给视图?

编辑:

谢谢你的回答。我看到其中几个声明组件位于同一页面中,但是当我查看 CodeIgniter 之类的内容时,我看到模型、视图和控制器的三个单独的 PHP 页面。

How do PHP programs pass values between model, view, and controller pages? For example, if a controller had an array, how does it pass that to the view?

EDIT:

Thank your answers. I see a couple of them stating the components are in the same page, but when I look at something like CodeIgniter, I see three separate PHP pages for model, view, and controller.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

风蛊 2024-10-02 18:21:17

通常,您的控制器将创建一个视图对象,当它创建该视图对象时,它会传递信息。

<?php

class Controller {
    public function __construct() {
        $arr = array("a","b","c");

        $myView = new View($arr);
    }
}

class View {

    private $content;

    public function __construct($content) {
        $this->content = $content;
        include_once('myPage.inc.html');
    }
}


?>

Usually your controller will create a view object and when it creates that view object it passes the information.

<?php

class Controller {
    public function __construct() {
        $arr = array("a","b","c");

        $myView = new View($arr);
    }
}

class View {

    private $content;

    public function __construct($content) {
        $this->content = $content;
        include_once('myPage.inc.html');
    }
}


?>
橘亓 2024-10-02 18:21:17

CodeIgniter 与大多数 PHP MVC 框架一样,带有一个视图“引擎”。换句话说,框架中有一个类负责从控制器加载数据并将其传输到视图。

具体到 CodeIgniter,这些调用如下所示:

$data = array(
           'title' => 'My Title',
           'heading' => 'My Heading',
           'message' => 'My Message'
      );

$this->load->view('blogview', $data);

然后您的视图将是一个单独的 php 页面,在本例中是 blogview.php。它可能看起来像这样:

<html>
   <head><title><?= $title ?></title></head>
   <body>
      <h2><?= $heading ?></h2>
      <p><?= $message ?></p>
   </body>
</html>

负责在控制器和视图之间传输数据的部分是 CodeIgniter 内部的视图引擎(或类)。它从控制器获取该数组并将其反序列化以供视图使用。

那么为什么要两个单独的文件呢? MVC 范例是这样的,根据设计,您希望业务逻辑与 UI 分离。如果您不使用数据库做太多事情,则不需要合并 MVC 的模型部分。但当您想要进一步将代码的数据访问部分与业务逻辑(为用户操作数据的内容)分开时,它就在那里。在这种情况下,您将获得 3 个独立的文件;模型、控制器、视图。

所以不,这些组件并不都在同一页面中,尽管它们当然可以。但是,通过使用 MVC 构建程序,您可以干净整洁地分离应用程序的操作。这样,您可以一次只处理一层,而不会影响其他层。例如,当您弄清楚用户无法登录的原因时,您的 CSS 人员可能正在使网站看起来很漂亮。

CodeIgniter, like most PHP MVC frameworks, comes with a View "engine". In otherwords, there's a class in the framework responsible for loading and transferring data from your controller to the view.

Specific to CodeIgniter, those calls look like this:

$data = array(
           'title' => 'My Title',
           'heading' => 'My Heading',
           'message' => 'My Message'
      );

$this->load->view('blogview', $data);

Your view would then be a separate php page, in this case blogview.php. It may look like this:

<html>
   <head><title><?= $title ?></title></head>
   <body>
      <h2><?= $heading ?></h2>
      <p><?= $message ?></p>
   </body>
</html>

The part responsible for transferring the data between the controller and the view is the View engine (or class) internal to CodeIgniter. It takes that array from the controller and deserializes it for the view.

So why two separate files? The MVC paradigm is such that, by design, you want your business logic separated from your UI. You don't need to incorporate the Model part of MVC if you aren't doing much with a database. But it's there when you want to further separate the data access portions of your code from your business logic (the stuff that manipulates the data for the user). In that case, you've got your 3 separate files; model, controller, view.

So no, the components aren't all in the same page, though they certainly could be. But by structuring your program using MVC, you separate the operations of your application cleanly and neatly. That way, you can work in one layer at a time without effecting the other layers. Your CSS guy could be making the site look pretty while you figure out why the user can't log in, for example.

迷路的信 2024-10-02 18:21:17

我希望约翰尼早就找到了我现在正在寻找的答案,但我可以提供有关如何做到这一点的见解,但效果并不令人满意!您可以将一个信息从一个文件(例如收集站点用户输入的数据的“视图”组件)传递到另一个文件(例如检查/验证表单数据并将其发送回表单的“模型”组件)以供修订或将其存储在数据库中)。表单值可以通过 POST 或 GET 数组发送,“action”属性确定哪个文件接收数据,例如

<form action = 'form-exec.php' method = 'POST'>
---some set of  possible user inputs goes here
<input name='submit' type='submit' value='Go'>
</form>

处理后,您可能希望将一些数据返回到表单 - 例如需要修改的用户输入值,或成功消息。您可以将该数据存储在会话变量中,并从“视图”页面上的这些变量中恢复它。那么,如何返回“查看”页面呢?现在,我在这里是因为我已经看到了它的使用并且自己也使用过它,但是当我读到这一点时我感到非常震惊,显然,传输是通过慢速的互联网http请求进行的 - 即使传输是到同一个文件中的文件服务器上的目录!好吧,返回“视图”组件的令人不满意的方法是这样几行 PHP 代码:

header("location: theinputform.php");
    exit;

它确实有效,但肯定有更好的方法吗?我看到有人“咆哮”说你应该只使用包含,但我不明白如何做返回页面顶部并根据新条件重新创建它的合理日常操作。例如,如果我刚刚登录了一个用户,我不想这次显示登录邀请。包含是有条件地向页面添加内容的简单方法,但我还没有找到比上面更好的简单返回顶部的方法。有人对此有任何见解或知识吗?正如 OP 所说,Johnny 和我想要做与 MVC 相同的事情,但没有使用任何类型的 MVC 框架。顺便说一句,有几本书和教程只是使用上述“标题”方法。

好的,编辑:您可以使用表单的“action”属性从表单(即“视图”页面)进行表单处理,如上所述。如果“模型”页面不输出 html 而只是“执行操作”,则您可以简单地包含您希望在完成后转到(或返回)的“视图”页面。无论如何,我认为是这样!正想尝试一下...

I hope Johnny has long ago found the answer that I'm searching for now, but I can supply an insight on how to do it unsatisfactorily! You can pass from one info from one file (say a 'view' component that collects data input by a site user) to another file (say a 'model' component that checks/validates the form data and either sends it back to the form for revision or stores it in a database). Form values can be sent via the POST or GET arrays and the 'action' attribute determines which file receives the data e.g.

<form action = 'form-exec.php' method = 'POST'>
---some set of  possible user inputs goes here
<input name='submit' type='submit' value='Go'>
</form>

After processing, you may well want to return some data to the form - such as the user input values that need to be amended, or a success message. You can store that data in session variables and recover it from those variables on the 'view' page. So, how do you get back to the 'view' page? Now, I'm here because I have seen this used and have used it myself but was pretty horrified to read that, apparently, the transfer goes via a dog-slow internet http request - even when the transfer is to a file in the same directory on the server! Okay, so the UNSATISFACTORY way to get back to your 'view' component is a couple of PHP lines like this:

header("location: theinputform.php");
    exit;

It does work, but there must be a better way, surely? I have seen a 'rant' from someone saying that you should just use an include, but I can't understand how to do the reasonably everyday thing of going back to the top of a page and recreating it according to the new conditions. For example, if I just logged a User in I don't want to be showing an invitation to login this time around. Includes are the no-brainer for conditionally ADDING something to a page, but I haven't found a better way to simply return to the top than the above. Does anyone have any insight or knowledge on this? As the OP states, Johnny and I want to do the same as a MVC but are not using a MVC framework of any kind. There are several books and tutorials out there that simply use the above 'headers' method, btw.

Okay, edit: You get from a form (i.e. a 'view' page) to the form processing using the form's 'action' attribute, as above. If the 'model' page outputs no html and just 'does things', you can simply include the 'view' page that you wish to go to (or return to) on completion. I think so, anyway! Just about to try that...

靑春怀旧 2024-10-02 18:21:17

我自己也曾为这个问题而苦苦挣扎。近十年后我又回到了 php 编程。我在将 PHP MVC 框架部署到实验服务器时遇到了几个问题,因此我最终自己构建了一个简单的 MVC 变体。

在我的简单设计(前端)中,控制器与模型交互以填充有效负载对象并将其传递给视图。每个视图都在单独的 PHP 文件中实现,因此控制器使用 include 来“加载”所需的视图。
然后,视图可以通过有效负载对象的指定名称 ($dataId) 访问数据。

class Controller {
        public $model;
        ...
        public function display($viewId,$dataId,$data)
        {
          $url = $this->getViewURL($viewId);
          $this->loadView($url,$dataId,$data);              
        }

        public function getViewURL($key)
        {
            $url = 'view/list_view.php';

            if($key == 'create')
            {
                $url = 'view/create_view.php';
            }
            else if($key == 'delete')
            {
                $url = 'view/delete_view.php';
            }


            return $url;            
        }

        public function loadView($url,$variable_name, $data)
        {
            $variable_name = $data;
            include $url;
        }
}

I struggled with this question myself. I had returned to php programming after nearly a decade. I ran into couple of issues deploying PHP MVC frameworks into an experimental server so I ended up building a simple MVC variant myself.

In my simple design (front) controller interacts with the Model to populate a payload object and passes it to the view. Each view is implemented in a separate PHP file so controller uses include, to "load" the desired view.
The view then can access the data via the designated name ($dataId) for the payload object.

class Controller {
        public $model;
        ...
        public function display($viewId,$dataId,$data)
        {
          $url = $this->getViewURL($viewId);
          $this->loadView($url,$dataId,$data);              
        }

        public function getViewURL($key)
        {
            $url = 'view/list_view.php';

            if($key == 'create')
            {
                $url = 'view/create_view.php';
            }
            else if($key == 'delete')
            {
                $url = 'view/delete_view.php';
            }


            return $url;            
        }

        public function loadView($url,$variable_name, $data)
        {
            $variable_name = $data;
            include $url;
        }
}
半城柳色半声笛 2024-10-02 18:21:17

模型、视图和控制器不是单独的页面,而是一页。
所以,不需要“传递”任何东西

model, view, and controller are not separate pages but one page.
So, no need to "pass" anything

情丝乱 2024-10-02 18:21:17

你可以使用像 smarty 这样的模板引擎来将视图与控制器和模型分开。

并使用 smarty 的分配方法将变量传递给模板。

u can use a template engine like smarty to seperate views from controllers and models.

and pass variables to your template using assign method of smarty for example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文