tags:

views:

303

answers:

5

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

+1  A: 

you should try an mvc-framework for php, like CodeIgniter or Zend Framework or CakePHP

Here's a Hello World-example with CodeIgniter.

Natrium
+1 Just watched the CodeIgniter video, it's really straight forward and clear
Gavin Miller
+4  A: 

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.

Pascal MARTIN
I'm sure he has no customer requirement for a "Hello, World" application.
Ionuț G. Stan
+2  A: 

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>
DisgruntledGoat
+3  A: 

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.

Ionuț G. Stan
hm, why does the view consist of a function with so much php and so few xhtml?
tharkun
I don't see "Hello" or "world"
Natrium
@Natrium, any constructive comments?
Ionuț G. Stan
@tharkun, so much PHP? Is just a for loop and some concatenation. I didn't want to introduce a templating system based on PHP. I wanted a straight, clear example of separation of concerns. Too much markup would have created useless noise in my opinion.
Ionuț G. Stan
A: 

This answer "link text" by "Ionut G. Stan" is very easy to understand and follow about the MVC in PHP, But I don't know how actually can put it into the use? Any help how can run that PHP script? Thanks

Steve, add some comments to my answer about your difficulties. I'll try to answer them.
Ionuț G. Stan