Immanuel

Friday, July 17, 2015

PHP MVC

VC - > Model View Controller

It is the very famous design used by most developers, it help the developer to reuse the components and to create the loosely coupled web application.


The above picture shows how this MVC Works.

We will create the three folder called model,view,controller.
The folder and files which we will be using are




Controller is the one which handle the request and give appropriate response page.

Controller.php




  

include_once("model/Model.php");

class Controller {
     public $model;

     public function __construct()  
     {  
          $this->model = new Model();
     } 
     public function invoke()
     {
          if (!isset($_GET['book']))
          {
               // no special book is requested, we'll show a list of all available books
               $books = $this->model->getBookList();
               include 'view/booklist.php';
          }
          else
          {
               // show the requested book
               $book = $this->model->getBook($_GET['book']);
               include 'view/viewbook.php';
          }
     }
}

?>

Model
 Model is the basic layer where the data lies

Book.php

class Book {
public $title;
public $author;
public $description;
public function __construct($title, $author, $description)  
    {  
        $this->title = $title;
   $this->author = $author;
   $this->description = $description;
    } 
}

?>

Model.php

include_once("model/Book.php");
class Model {
public function getBookList()
{
// here goes some hardcoded values to simulate the database
return array(
"Jungle Book" => new Book("Jungle Book", "R. Kipling", "A classic book."),
"Moonwalker" => new Book("Moonwalker", "J. Walker", ""),
"PHP for Dummies" => new Book("PHP for Dummies", "Some Smart Guy", "")
);
}
public function getBook($title)
{
// we use the previous function to get all the books and then we return the requested one.
// in a real life scenario this will be done through a db select command
$allBooks = $this->getBookList();
return $allBooks[$title];
}
}
?>

View

It is the output which user can view at client side

booklist.php



Title
Author
Description


foreach ($books as $title => $book)
{
echo '
'.$book->title.'
'.$book->author.'
'.$book->description.'
';
}

?>


viewbook.php




echo 'Title:' . $book->title . '
';
echo 'Author:' . $book->author . '
';
echo 'Description:' . $book->description . '
';

?>


Root File

This file will be the index of this web application, this is only file name that user can see in web browser.

index.php





Happy Hacking :)





1 comment:

Twitter Bird Gadget