Use MVC to echo Hello World!

2018-07-11 13:32:30
tengfei
6728
Last edited by tengfei on 2019-09-16 14:10:42

In the last article, we have learned to echo Hello World! in a simple way. Now let's see how to echo Hello World! using MVC.


1.  Hello World! with control.php only

In the last article, Hello World!is printed in control directly.


<?php
class hello extends control
{
    public function world()
    {
        echo 'Hello world';
    }
}


2. Hello World!with a model layer

Now we use a model. Create model.php.


<?php
class helloModel extends model
{
    public function world()
    {
        return 'Hello world!';
    }
}



Then we have to change a little in control.


public function world()
{
    echo $this->hello->world();
}


zentaoPHP will automatically load the model for the current module and generate the object for this model. Then use  $this->hello (module name) in control to refer to the methods in this model.


Visit http://localhost/zentaophp/hello-world, do you see Hello World now?


3. Hello World!with a view layer

The naming convention for templates in zentaoPHP is as follows,

  • View files are under the directory of view in each module.
  • The naming convention of a view file is method.module.php. For example, index.html is what we want to visit. Then the template file should be named index.html.php.


First, change the control file.


public function world()
{
    $this->view->helloworld = $this->hello->world();
    $this->display();
}



Then create view/world.html.php


<?php
echo $helloworld;
?>



Control will assign the variables returned by the model to view files. Then call the display to show the template file. Refresh. Do you see it now?


If yes, congratulations! You have done learning the basic and core part of zentaoPHP.


Write a Comment
Comment will be posted after it is reviewed.