SlideShare a Scribd company logo
1 of 26
PHP MVCPHP MVC
Reggie Niccolo SantosReggie Niccolo Santos
UP ITDCUP ITDC

DefinitionDefinition

Sample MVC applicationSample MVC application

AdvantagesAdvantages
OutlineOutline

Model-View-ControllerModel-View-Controller

Most used architectural pattern for today's webMost used architectural pattern for today's web
applicationsapplications

Originally described in terms of a design patternOriginally described in terms of a design pattern
for use with Smalltalk by Trygyve Reenskaug infor use with Smalltalk by Trygyve Reenskaug in
19791979

The paper was published under the titleThe paper was published under the title
”Applications Programming in Smalltalk-80:”Applications Programming in Smalltalk-80:
How to use Model-View-Controller”How to use Model-View-Controller”
MVCMVC
MVCMVC

Responsible for managing the dataResponsible for managing the data

Stores and retrieves entities used by anStores and retrieves entities used by an
application, usually from a database but can alsoapplication, usually from a database but can also
include invocations of external web services orinclude invocations of external web services or
APIsAPIs

Contains the logic implemented by theContains the logic implemented by the
application (business logic)application (business logic)
ModelModel

Responsible to display the data provided by theResponsible to display the data provided by the
model in a specific formatmodel in a specific format
View (Presentation)View (Presentation)

Handles the model and view layers to workHandles the model and view layers to work
togethertogether

Receives a request from the client, invokes theReceives a request from the client, invokes the
model to perform the requested operations andmodel to perform the requested operations and
sends the data to the viewsends the data to the view
ControllerController
MVC Collaboration DiagramMVC Collaboration Diagram
MVC Sequence DiagramMVC Sequence Diagram
Sample MVC ApplicationSample MVC Application
require_once("controller/Controller.php");require_once("controller/Controller.php");
$controller = new Controller();$controller = new Controller();
$controller->invoke();$controller->invoke();
Entry point - index.phpEntry point - index.php

The application entry point will be index.phpThe application entry point will be index.php

The index.php file will delegate all the requestsThe index.php file will delegate all the requests
to the controllerto the controller
Entry point - index.phpEntry point - index.php
require_once("model/Model.php");require_once("model/Model.php");
cclass Controller {lass Controller {
public $model;public $model;
public function __construct()public function __construct()
{{
$this->model = new Model();$this->model = new Model();
}}
// continued...// continued...
Controller – controller/Controller.phpController – controller/Controller.php
require_once("model/Model.php");require_once("model/Model.php");
cclass Controller {lass Controller {
public $model;public $model;
public function __construct()public function __construct()
{{
$this->model = new Model();$this->model = new Model();
}}
// continued...// continued...
Controller – controller/Controller.phpController – controller/Controller.php
pupublic function invoke()blic function invoke()
{{
if (!isset($_GET['book']))if (!isset($_GET['book']))
{{
// no special book is requested, we'll// no special book is requested, we'll
show a list of all available booksshow a list of all available books
$books = $this->model->getBookList();$books = $this->model->getBookList();
include 'view/booklist.php';include 'view/booklist.php';
}}
elseelse
{{
// show the requested book// show the requested book
$book = $this->model->getBook$book = $this->model->getBook
($_GET['book']);($_GET['book']);
include 'view/viewbook.php';include 'view/viewbook.php';
}}
}}
}}
Controller – controller/Controller.phpController – controller/Controller.php

The controller is the first layer which takes aThe controller is the first layer which takes a
request, parses it, initializes and invokes therequest, parses it, initializes and invokes the
model, takes the model response and sends it tomodel, takes the model response and sends it to
the view or presentation layerthe view or presentation layer
Controller – controller/Controller.phpController – controller/Controller.php
class Book {class Book {
public $title;public $title;
public $author;public $author;
public $description;public $description;
public function __construct($title, $author,public function __construct($title, $author,
$description)$description)
{{
$this->title = $title;$this->title = $title;
$this->author = $author;$this->author = $author;
$this->description = $description;$this->description = $description;
}}
}}
Model – model/Book.phpModel – model/Book.php

Their sole purpose is to keep dataTheir sole purpose is to keep data

Depending on the implementation, entity objectsDepending on the implementation, entity objects
can be replaced by XML or JSON chunk of datacan be replaced by XML or JSON chunk of data

It is recommended that entities do notIt is recommended that entities do not
encapsulate any business logicencapsulate any business logic
Model - EntitiesModel - Entities
require_once("model/Book.php");require_once("model/Book.php");
class Model {class Model {
public function getBookList()public function getBookList()
{{
// here goes some hardcoded values to simulate// here goes some hardcoded values to simulate
the databasethe database
return array(return array(
"Jungle Book" => new Book("Jungle Book", "R."Jungle Book" => new Book("Jungle Book", "R.
Kipling", "A classic book."),Kipling", "A classic book."),
"Moonwalker" => new Book("Moonwalker", "J."Moonwalker" => new Book("Moonwalker", "J.
Walker", ""),Walker", ""),
"PHP for Dummies" => new Book("PHP for"PHP for Dummies" => new Book("PHP for
Dummies", "Some Smart Guy", "")Dummies", "Some Smart Guy", "")
););
}}
// continued...// continued...
Model – model/Model.phpModel – model/Model.php
public function getBook($title)public function getBook($title)
{{
// we use the previous function to get all the// we use the previous function to get all the
books and then we return the requested one.books and then we return the requested one.
// in a real life scenario this will be done// in a real life scenario this will be done
through a db select commandthrough a db select command
$allBooks = $this->getBookList();$allBooks = $this->getBookList();
return $allBooks[$title];return $allBooks[$title];
}}
}}
Model – model/Model.phpModel – model/Model.php

In a real-world scenario, the model will include allIn a real-world scenario, the model will include all
the entities and the classes to persist data intothe entities and the classes to persist data into
the database, and the classes encapsulating thethe database, and the classes encapsulating the
business logicbusiness logic
ModelModel
<html><html>
<head></head><head></head>
<body><body>
<?php<?php
echo 'Title:' . $book->title . '<br/>';echo 'Title:' . $book->title . '<br/>';
echo 'Author:' . $book->author . '<br/>';echo 'Author:' . $book->author . '<br/>';
echo 'Description:' . $book->description .echo 'Description:' . $book->description .
'<br/>';'<br/>';
?>?>
</body></body>
</html></html>
View – view/viewbook.phpView – view/viewbook.php
<html><html>
<head></head><head></head>
<body><body>
<table><tbody><table><tbody>
<tr><td>Title</td><td>Author</td><tr><td>Title</td><td>Author</td>
<td>Description</td></tr><td>Description</td></tr>
<?php<?php
foreach ($books as $title => $book)foreach ($books as $title => $book)
{{
echo '<tr><td><a href="index.php?book='.echo '<tr><td><a href="index.php?book='.
$book->title.'">'.$book->title.'</a></td><td>'.$book->title.'">'.$book->title.'</a></td><td>'.
$book->author.'</td><td>'.$book-$book->author.'</td><td>'.$book-
>description.'</td></tr>';>description.'</td></tr>';
}}
?>?>
</tbody></table></tbody></table>
</body></body>
</html></html>
View – view/booklist.phpView – view/booklist.php

Responsible for formatting the data receivedResponsible for formatting the data received
from the model in a form accessible to the userfrom the model in a form accessible to the user

The data can come in different formats from theThe data can come in different formats from the
model: simple objects (sometimes called Valuemodel: simple objects (sometimes called Value
Objects), XML structures, JSON, etc.Objects), XML structures, JSON, etc.
ViewView

The Model and View are separated, making theThe Model and View are separated, making the
application more flexibleapplication more flexible

The Model and View can be changed separately,The Model and View can be changed separately,
or replacedor replaced

Each module can be tested and debuggedEach module can be tested and debugged
separatelyseparately
AdvantagesAdvantages
http://php-html.net/tutorials/model-view-controller-in-phttp://php-html.net/tutorials/model-view-controller-in-p
http://www.htmlgoodies.com/beyond/php/article.php/3http://www.htmlgoodies.com/beyond/php/article.php/3
http://www.phpro.org/tutorials/Model-View-Controller-Mhttp://www.phpro.org/tutorials/Model-View-Controller-M
http://www.particletree.com/features/4-layers-of-separhttp://www.particletree.com/features/4-layers-of-separ
ReferencesReferences

More Related Content

What's hot

Laravel Design Patterns
Laravel Design PatternsLaravel Design Patterns
Laravel Design PatternsBobby Bouwmann
 
Un exemple élémentaire d'application MVC en PHP
Un exemple élémentaire d'application MVC en PHPUn exemple élémentaire d'application MVC en PHP
Un exemple élémentaire d'application MVC en PHPKristen Le Liboux
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHPVibrant Technologies & Computers
 
Laravel presentation
Laravel presentationLaravel presentation
Laravel presentationToufiq Mahmud
 
cours j2ee -présentation
cours  j2ee -présentationcours  j2ee -présentation
cours j2ee -présentationYassine Badri
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentationivpol
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentationritika1
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Edureka!
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized军 沈
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingAhmed Swilam
 

What's hot (20)

Laravel Design Patterns
Laravel Design PatternsLaravel Design Patterns
Laravel Design Patterns
 
Un exemple élémentaire d'application MVC en PHP
Un exemple élémentaire d'application MVC en PHPUn exemple élémentaire d'application MVC en PHP
Un exemple élémentaire d'application MVC en PHP
 
Support de Cours JSF2 Première partie Intégration avec Spring
Support de Cours JSF2 Première partie Intégration avec SpringSupport de Cours JSF2 Première partie Intégration avec Spring
Support de Cours JSF2 Première partie Intégration avec Spring
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Express js
Express jsExpress js
Express js
 
JNDI
JNDIJNDI
JNDI
 
MVC in PHP
MVC in PHPMVC in PHP
MVC in PHP
 
Support programmation orientée aspect mohamed youssfi (aop)
Support programmation orientée aspect mohamed youssfi (aop)Support programmation orientée aspect mohamed youssfi (aop)
Support programmation orientée aspect mohamed youssfi (aop)
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
Laravel presentation
Laravel presentationLaravel presentation
Laravel presentation
 
Express node js
Express node jsExpress node js
Express node js
 
cours j2ee -présentation
cours  j2ee -présentationcours  j2ee -présentation
cours j2ee -présentation
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 

Similar to PHP MVC

Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's CodeWildan Maulana
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For ManagersAgileThought
 
Web internship Yii Framework
Web internship  Yii FrameworkWeb internship  Yii Framework
Web internship Yii FrameworkNoveo
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalystsvilen.ivanov
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...LEDC 2016
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindValentine Matsveiko
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Michelangelo van Dam
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkBo-Yi Wu
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalystdwm042
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Phpfunkatron
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 
深入淺出 MVC
深入淺出 MVC深入淺出 MVC
深入淺出 MVCJace Ju
 
Drupal Best Practices
Drupal Best PracticesDrupal Best Practices
Drupal Best Practicesmanugoel2003
 
How to Create and Load Model in Laravel
How to Create and Load Model in LaravelHow to Create and Load Model in Laravel
How to Create and Load Model in LaravelYogesh singh
 
DDD on example of Symfony (Webcamp Odessa 2014)
DDD on example of Symfony (Webcamp Odessa 2014)DDD on example of Symfony (Webcamp Odessa 2014)
DDD on example of Symfony (Webcamp Odessa 2014)Oleg Zinchenko
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Eric Palakovich Carr
 
JDay Deutschland 2015 - PHP Design Patterns in Joomla!
JDay Deutschland 2015 - PHP Design Patterns in Joomla!JDay Deutschland 2015 - PHP Design Patterns in Joomla!
JDay Deutschland 2015 - PHP Design Patterns in Joomla!Yves Hoppe
 

Similar to PHP MVC (20)

Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For Managers
 
Web internship Yii Framework
Web internship  Yii FrameworkWeb internship  Yii Framework
Web internship Yii Framework
 
Yii Introduction
Yii IntroductionYii Introduction
Yii Introduction
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mind
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Php
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
深入淺出 MVC
深入淺出 MVC深入淺出 MVC
深入淺出 MVC
 
Drupal Best Practices
Drupal Best PracticesDrupal Best Practices
Drupal Best Practices
 
How to Create and Load Model in Laravel
How to Create and Load Model in LaravelHow to Create and Load Model in Laravel
How to Create and Load Model in Laravel
 
AngularJS Basic Training
AngularJS Basic TrainingAngularJS Basic Training
AngularJS Basic Training
 
DDD on example of Symfony (Webcamp Odessa 2014)
DDD on example of Symfony (Webcamp Odessa 2014)DDD on example of Symfony (Webcamp Odessa 2014)
DDD on example of Symfony (Webcamp Odessa 2014)
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
JDay Deutschland 2015 - PHP Design Patterns in Joomla!
JDay Deutschland 2015 - PHP Design Patterns in Joomla!JDay Deutschland 2015 - PHP Design Patterns in Joomla!
JDay Deutschland 2015 - PHP Design Patterns in Joomla!
 

More from Reggie Niccolo Santos (15)

Securing PHP Applications
Securing PHP ApplicationsSecuring PHP Applications
Securing PHP Applications
 
Introduction to Web 2.0
Introduction to Web 2.0Introduction to Web 2.0
Introduction to Web 2.0
 
UI / UX Engineering for Web Applications
UI / UX Engineering for Web ApplicationsUI / UX Engineering for Web Applications
UI / UX Engineering for Web Applications
 
Computability - Tractable, Intractable and Non-computable Function
Computability - Tractable, Intractable and Non-computable FunctionComputability - Tractable, Intractable and Non-computable Function
Computability - Tractable, Intractable and Non-computable Function
 
Algorithms - Aaron Bloomfield
Algorithms - Aaron BloomfieldAlgorithms - Aaron Bloomfield
Algorithms - Aaron Bloomfield
 
Program Logic Formulation - Ohio State University
Program Logic Formulation - Ohio State UniversityProgram Logic Formulation - Ohio State University
Program Logic Formulation - Ohio State University
 
Abstract Data Types
Abstract Data TypesAbstract Data Types
Abstract Data Types
 
Computational Thinking and Data Representations
Computational Thinking and Data RepresentationsComputational Thinking and Data Representations
Computational Thinking and Data Representations
 
Number Systems
Number SystemsNumber Systems
Number Systems
 
Introduction to Game Development
Introduction to Game DevelopmentIntroduction to Game Development
Introduction to Game Development
 
Application Testing
Application TestingApplication Testing
Application Testing
 
Application Security
Application SecurityApplication Security
Application Security
 
MySQL Transactions
MySQL TransactionsMySQL Transactions
MySQL Transactions
 
MySQL Cursors
MySQL CursorsMySQL Cursors
MySQL Cursors
 
MySQL Views
MySQL ViewsMySQL Views
MySQL Views
 

Recently uploaded

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 

PHP MVC

  • 1. PHP MVCPHP MVC Reggie Niccolo SantosReggie Niccolo Santos UP ITDCUP ITDC
  • 2.  DefinitionDefinition  Sample MVC applicationSample MVC application  AdvantagesAdvantages OutlineOutline
  • 3.  Model-View-ControllerModel-View-Controller  Most used architectural pattern for today's webMost used architectural pattern for today's web applicationsapplications  Originally described in terms of a design patternOriginally described in terms of a design pattern for use with Smalltalk by Trygyve Reenskaug infor use with Smalltalk by Trygyve Reenskaug in 19791979  The paper was published under the titleThe paper was published under the title ”Applications Programming in Smalltalk-80:”Applications Programming in Smalltalk-80: How to use Model-View-Controller”How to use Model-View-Controller” MVCMVC
  • 5.  Responsible for managing the dataResponsible for managing the data  Stores and retrieves entities used by anStores and retrieves entities used by an application, usually from a database but can alsoapplication, usually from a database but can also include invocations of external web services orinclude invocations of external web services or APIsAPIs  Contains the logic implemented by theContains the logic implemented by the application (business logic)application (business logic) ModelModel
  • 6.  Responsible to display the data provided by theResponsible to display the data provided by the model in a specific formatmodel in a specific format View (Presentation)View (Presentation)
  • 7.  Handles the model and view layers to workHandles the model and view layers to work togethertogether  Receives a request from the client, invokes theReceives a request from the client, invokes the model to perform the requested operations andmodel to perform the requested operations and sends the data to the viewsends the data to the view ControllerController
  • 8. MVC Collaboration DiagramMVC Collaboration Diagram
  • 9. MVC Sequence DiagramMVC Sequence Diagram
  • 10. Sample MVC ApplicationSample MVC Application
  • 11. require_once("controller/Controller.php");require_once("controller/Controller.php"); $controller = new Controller();$controller = new Controller(); $controller->invoke();$controller->invoke(); Entry point - index.phpEntry point - index.php
  • 12.  The application entry point will be index.phpThe application entry point will be index.php  The index.php file will delegate all the requestsThe index.php file will delegate all the requests to the controllerto the controller Entry point - index.phpEntry point - index.php
  • 13. require_once("model/Model.php");require_once("model/Model.php"); cclass Controller {lass Controller { public $model;public $model; public function __construct()public function __construct() {{ $this->model = new Model();$this->model = new Model(); }} // continued...// continued... Controller – controller/Controller.phpController – controller/Controller.php
  • 14. require_once("model/Model.php");require_once("model/Model.php"); cclass Controller {lass Controller { public $model;public $model; public function __construct()public function __construct() {{ $this->model = new Model();$this->model = new Model(); }} // continued...// continued... Controller – controller/Controller.phpController – controller/Controller.php
  • 15. pupublic function invoke()blic function invoke() {{ if (!isset($_GET['book']))if (!isset($_GET['book'])) {{ // no special book is requested, we'll// no special book is requested, we'll show a list of all available booksshow a list of all available books $books = $this->model->getBookList();$books = $this->model->getBookList(); include 'view/booklist.php';include 'view/booklist.php'; }} elseelse {{ // show the requested book// show the requested book $book = $this->model->getBook$book = $this->model->getBook ($_GET['book']);($_GET['book']); include 'view/viewbook.php';include 'view/viewbook.php'; }} }} }} Controller – controller/Controller.phpController – controller/Controller.php
  • 16.  The controller is the first layer which takes aThe controller is the first layer which takes a request, parses it, initializes and invokes therequest, parses it, initializes and invokes the model, takes the model response and sends it tomodel, takes the model response and sends it to the view or presentation layerthe view or presentation layer Controller – controller/Controller.phpController – controller/Controller.php
  • 17. class Book {class Book { public $title;public $title; public $author;public $author; public $description;public $description; public function __construct($title, $author,public function __construct($title, $author, $description)$description) {{ $this->title = $title;$this->title = $title; $this->author = $author;$this->author = $author; $this->description = $description;$this->description = $description; }} }} Model – model/Book.phpModel – model/Book.php
  • 18.  Their sole purpose is to keep dataTheir sole purpose is to keep data  Depending on the implementation, entity objectsDepending on the implementation, entity objects can be replaced by XML or JSON chunk of datacan be replaced by XML or JSON chunk of data  It is recommended that entities do notIt is recommended that entities do not encapsulate any business logicencapsulate any business logic Model - EntitiesModel - Entities
  • 19. require_once("model/Book.php");require_once("model/Book.php"); class Model {class Model { public function getBookList()public function getBookList() {{ // here goes some hardcoded values to simulate// here goes some hardcoded values to simulate the databasethe database return array(return array( "Jungle Book" => new Book("Jungle Book", "R."Jungle Book" => new Book("Jungle Book", "R. Kipling", "A classic book."),Kipling", "A classic book."), "Moonwalker" => new Book("Moonwalker", "J."Moonwalker" => new Book("Moonwalker", "J. Walker", ""),Walker", ""), "PHP for Dummies" => new Book("PHP for"PHP for Dummies" => new Book("PHP for Dummies", "Some Smart Guy", "")Dummies", "Some Smart Guy", "") );); }} // continued...// continued... Model – model/Model.phpModel – model/Model.php
  • 20. public function getBook($title)public function getBook($title) {{ // we use the previous function to get all the// we use the previous function to get all the books and then we return the requested one.books and then we return the requested one. // in a real life scenario this will be done// in a real life scenario this will be done through a db select commandthrough a db select command $allBooks = $this->getBookList();$allBooks = $this->getBookList(); return $allBooks[$title];return $allBooks[$title]; }} }} Model – model/Model.phpModel – model/Model.php
  • 21.  In a real-world scenario, the model will include allIn a real-world scenario, the model will include all the entities and the classes to persist data intothe entities and the classes to persist data into the database, and the classes encapsulating thethe database, and the classes encapsulating the business logicbusiness logic ModelModel
  • 22. <html><html> <head></head><head></head> <body><body> <?php<?php echo 'Title:' . $book->title . '<br/>';echo 'Title:' . $book->title . '<br/>'; echo 'Author:' . $book->author . '<br/>';echo 'Author:' . $book->author . '<br/>'; echo 'Description:' . $book->description .echo 'Description:' . $book->description . '<br/>';'<br/>'; ?>?> </body></body> </html></html> View – view/viewbook.phpView – view/viewbook.php
  • 23. <html><html> <head></head><head></head> <body><body> <table><tbody><table><tbody> <tr><td>Title</td><td>Author</td><tr><td>Title</td><td>Author</td> <td>Description</td></tr><td>Description</td></tr> <?php<?php foreach ($books as $title => $book)foreach ($books as $title => $book) {{ echo '<tr><td><a href="index.php?book='.echo '<tr><td><a href="index.php?book='. $book->title.'">'.$book->title.'</a></td><td>'.$book->title.'">'.$book->title.'</a></td><td>'. $book->author.'</td><td>'.$book-$book->author.'</td><td>'.$book- >description.'</td></tr>';>description.'</td></tr>'; }} ?>?> </tbody></table></tbody></table> </body></body> </html></html> View – view/booklist.phpView – view/booklist.php
  • 24.  Responsible for formatting the data receivedResponsible for formatting the data received from the model in a form accessible to the userfrom the model in a form accessible to the user  The data can come in different formats from theThe data can come in different formats from the model: simple objects (sometimes called Valuemodel: simple objects (sometimes called Value Objects), XML structures, JSON, etc.Objects), XML structures, JSON, etc. ViewView
  • 25.  The Model and View are separated, making theThe Model and View are separated, making the application more flexibleapplication more flexible  The Model and View can be changed separately,The Model and View can be changed separately, or replacedor replaced  Each module can be tested and debuggedEach module can be tested and debugged separatelyseparately AdvantagesAdvantages