试图了解MVC。 我的网站的实施有多接近?

Very new to web programming still and I don't really have a specific question per se, but I was wondering how close this design is to how an MVC would be implemented under these conditions. Here is the template class that I am using. db.php just connects to the database.

I'd like to stay away from answers like "Use CodeIgniter, CakePHP, Zend Framework, et cetera" because I most likely am going to end up doing that eventually but for now I'd like to understand how to implement a barebones MVC pattern in a typical website using out of the box PHP and HTML. Also, I've read the wikipedia page for Model-view-controller and I am still confused as to how to apply it in this circumstance.

I don't really like the solution I am using right now because it still seems rather unorganized. I'm not sure what exactly I mean but it just seems to smell a bit. With the mass amount of variables it still seems rather messy and inelegant. It seems like many parts of the site struggle for access to other parts and that the overall design is a bit mucky. I am constantly passing large amounts of variables to constructors and the entire solution seems very inflexible. I don't know; I'm still somewhat confused as to what the controller is in this context or whether or not I even have one. Hopefully someone can alleviate all this confusion x_x

index.php

<?php
require('db.php');
require('header_model.php');
require('submissions_model.php');
require('template.php');

$headerModel = new HeaderModel();
$page = $headerModel->getPage();
$sort = $headerModel->getSort();
$search = $headerModel->getSearch();

$submissionsModel = new SubmissionsModel($sort, $page, $resultsPerPage, $search);
$submissions = $submissionsModel->getSubmissions();
$outcomeCount = $submissionsModel->getOutcomeCount();

$index_view = new Template('index_view.php', array(
    'header' => new Template('header.php'),
    'menu' => new Template('menu.php', array('sort' => $sort)),
    'submissions' => new Template('submissions.php', array('submissions' => $submissions)),
    'pagination' => new Template('pagination.php', array('page' => $page, 'resultsPerPage' => $resultsPerPage, 'outcomeCount' => $outcomeCount, 'sort' => $sort)),
    'footer' => new Template('footer.php')
));

$index_view->render();
?>

index_view.php snippet

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>My Website</title>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <link href="styles.css" rel="stylesheet" type="text/css"/>
        <link href="favicon.png" rel="shortcut icon" />
    </head>
    <body>
        <?php
        $this->header->render();
        $this->menu->render();
        $this->submissions->render();
        $this->pagination->render();
        $this->footer->render();
        ?>
    </body>
</html>

header_model.php snippet

public function getSearch() {
    if (isset($_GET['search']))
        return $_GET['search'];
    else
        return '';
}

submissions_model.php snippet

class SubmissionsModel {
    private $sort;
    private $page;
    private $resultsPerPage;
    private $search;

    public $submissions;
    public $outcomeCount;

    public function __construct($sort, $page, $resultsPerPage, $search) {
        $this->sort = $sort;
        $this->page = $page;
        $this->resultsPerPage = $resultsPerPage;
        $this->search = $search;

        $this->initialize();
    }

    private function initialize() {
        $submissionQuery = $this->getSubmissionQuery($this->search);
        $this->outcomeCount = mysql_num_rows($submissionQuery);
        $this->submissions = array();

        while ($row = mysql_fetch_assoc($submissionQuery)) {    
            $voteblock = $this->getVoteblock($row);
            $tags = $this->getTags($row);
            $commentCount = mysql_num_rows(mysql_query("SELECT id FROM comments WHERE submissionID = $row[id]"));
            $this->submissions[] = array('submission' => $row, 'upvote' => $voteblock['upvote'], 'votes' => $voteblock['votes'], 'downvote' => $voteblock['downvote'], 'tags' => $tags, 'commentCount' => $commentCount);
        }
    }
}
dongzuan4491
dongzuan4491 在你进入某事之前:“大约二十年前最初构想的MVC实际上并不适用于网络”
9 年多之前 回复

2个回答



我最近自己经历过这个窘境,经过一些试验和错误后,出现了以下设计模式实现,与ericacm的回答略有不同 :</ p>


  1. Front Controller处理所有传入请求并委派给所需的Controller。 这通常包括以某种方式将传入的URL映射到文件路径,但您也可能正在加载一些初始数据或基类,或者设置一些应用程序环境设置。</ p> </ li>

  2. 加载控制器后,在有新请求之前不再使用前端控制器。 (为了更好的词)'Main'控制器现在加载任何所需的Model类,并调用其中的方法以获取任何所需的数据。</ p> </ li>

  3. Model具有从数据源(即数据库)提取和处理所请求数据的方法。 除了其他模型和数据库连接之外,它无法访问任何内容。</ p> </ li>

  4. 加载数据后,Controller会加载相关的View类并将数据“推送”到变量中 在视图中保存。</ p> </ li>

  5. View类本身没有“更高”的逻辑功能,也无法访问模型或控制器方法。 实际上只提供通过各种 getSomeVar()</ code>或 renderSomeData()</ code>方法将数据处理到所需输出媒体(即html)的方法。</ p> < / li>

  6. 最后,Controller调用View的方法来呈现页面,此时Controllers作业完成。 View将加载必要的模板文件,这些文件将被解释为生成浏览器的输出。</ p> </ li>

  7. 模板文件主要是结构HTML,没有编程逻辑 。 数据仅通过调用View中的各种 renderSomething()</ code>方法加载到页面中。</ p> </ li>
    </ ol>



    我在这背后的想法是控制器应该控制( duh </ em>)所有东西!</ p>

    hth </ p>
    </ div>

展开原文

原文

I've recently been through this quandary myself and after some trial and error came to the following design pattern implementation which differs slightly from ericacm's answer:

  1. A Front Controller handles all incoming requests and delegates out to the required Controller. This usually consists of mapping the incoming URL to a file path somehow, but you may also be loading some initial data or base class, or setting up some application environment settings.

  2. Once the Controller is loaded the Front Controller isn't used again until there is a new request. The (for want of a better word) 'Main' Controller now loads any required Model class(es) and calls methods in them to obtain any required data.

  3. The Model has methods to extract and process the requested data from the data sources (i.e. a database). It cannot access anything except for other models and the DB connection.

  4. Once the data has been loaded the Controller loads the relevant View class and 'pushes' the data into variables held within the View.

  5. The View class itself has no 'higher' logic functions and has no access to the Model or Controller methods. It is really only there to provide methods for processing data into the required output media (i.e. html) through various getSomeVar() or renderSomeData() methods.

  6. Finally the Controller calls the View's method to render the page, at which point the Controllers job is done. The View will load the necessary template files which will be interpreted to produce the output for the browser.

  7. The template file(s) are mostly structure HTML with no programming logic. The data is only loaded into the page via calls to various renderSomething() methods within the View.


My thinking behind this was that the Controller should be in control (duh), of everything!

hth

展开原文

原文

MVC in the web world works like this:

  1. The controller handles the incoming request and generates the model.
  2. The view renders the HTML including the model data.

Taking that basic structure and expanding it a little further:

  1. A Front Controller handles all incoming requests. Based on the URL it selects a controller to call.
  2. The Controller generates the model and returns it to the Front Controller, along with (optionally) a view name.
  3. If the controller did not return a view name the Front Controller determines which view to render by convention (for example, which controller was used, or which URL was requested).
  4. The Front Controller delegates to the view (for example, using PHP include).

That is a super basic MVC setup that you can expand on.

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