用于PHP的MVC方法的Hello World示例

15 php model-view-controller

任何人都可以在PHP的MVC方法中提供一个非常简单的Hello World示例吗?

Ion*_*tan 34

这是一些"Hello,World"MVC:

模型

function get_users() {
    return array(
        'Foo',
        'Bar',
        'Baz',
    );
}
Run Code Online (Sandbox Code Playgroud)

视图

function users_template($users) {
    $html = '<ul>';

    foreach ($users as $user) {
        $html .= "<li>$user</li>";
    }

    $html .= '</ul>';

    return $html;
}
Run Code Online (Sandbox Code Playgroud)

调节器

function list_users() {
    $users = get_users();

    echo users_template($users);
}
Run Code Online (Sandbox Code Playgroud)

主要思想是将数据访问(模型)与数据表示(视图)分开.控制器应该只是将两者连接在一起.

  • 嗯,为什么视图包含一个具有如此多的PHP和如此少的xhtml的函数? (8认同)
  • @Natrium,有什么建设性的评论吗? (3认同)
  • @tharkun,那么多PHP?只是一个for循环和一些连接.我不想介绍一个基于PHP的模板系统.我想要一个关注点分离的直接明确的例子.在我看来,过多的标记会产生无用的噪音. (3认同)

Dis*_*oat 11

这是最基本的例子.index.php文件是控制器,从模型中获取一些数据,然后通过视图文件包含HTML.

/* index.php?section=articles&id=3 */

// includes functions for getting data from database
include 'model.php';

$section = $_GET['section'];
$id = $_GET['id'];

switch ( $section )
{
    case 'articles':
        $article = getArticle( $id );
        include 'article.view.php';
}
Run Code Online (Sandbox Code Playgroud)

.

/* article.view.php */

<html>
<head>
<title><?=$article['title']?></title>
</head>

<body>

<h1><?=$article['title']?></h1>
<p><?=$article['intro']?></p>
<?=$article['content']?>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)


Pas*_*TIN 6

Zend Framework快速入门是一个不错的"简单应用程序"的例子(不是"Hello World",但不是更多 - 使用MVC作为"Hello World"应用程序有点像使用核弹杀死一个bug),基于Zend Framework,并使用MVC.

之后,如果你想更进一步,你可以看一下电子书Survive The Deep End! - 仍在进行中,但无论如何都是一个有趣的阅读.

这与ZF有关; 我想你可以找到与Symfony或CakePHP等其他MVC框架相同的东西.