Hello World example in MVC approach to PHP [closed

2019-01-21 21:14发布

问题:

Can anyone provide a very simple example of Hello World in MVC approach to PHP?

回答1:

Here's some "Hello, World" MVC:

Model

function get_users() {
    return array(
        'Foo',
        'Bar',
        'Baz',
    );
}

View

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

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

    $html .= '</ul>';

    return $html;
}

Controller

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

    echo users_template($users);
}

The main idea is to keep separate the data access (model) from data presentation (view). The controller should be doing no more than wiring the two together.



回答2:

Here's the most basic example. Your index.php file is the controller, gets some data from the model, then includes the HTML via a view file.

/* 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';
}

.

/* article.view.php */

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

<body>

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

</body>
</html>


回答3:

The QuickStart of Zend Framework is a not too bad example of "simple application" (not an "Hello World", but not much more -- and using MVC for an "Hello World" application is a bit like using a nuclear bomb to kill a bug), based on Zend Framework, and using MVC.

After, if you want to get a bit farther, you can take a look at the electronic book Survive The Deep End! -- still work in progress, but an interesting read anyway.

That's with ZF ; I suppose you can find the same kind of stuff with other MVC Frameworks like Symfony or CakePHP.