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 (20)

Express node js
Express node jsExpress node js
Express node js
 
Introduction to Basic Concepts in Web
Introduction to Basic Concepts in WebIntroduction to Basic Concepts in Web
Introduction to Basic Concepts in Web
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Java beans
Java beansJava beans
Java beans
 
php
phpphp
php
 
MVC Framework
MVC FrameworkMVC Framework
MVC Framework
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
Express js
Express jsExpress js
Express js
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Introduction to mvc architecture
Introduction to mvc architectureIntroduction to mvc architecture
Introduction to mvc architecture
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Express JS Rest API Tutorial
Express JS Rest API TutorialExpress JS Rest API Tutorial
Express JS Rest API Tutorial
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and Authorization
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
5.state diagrams
5.state diagrams5.state diagrams
5.state diagrams
 
Vue.js
Vue.jsVue.js
Vue.js
 

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

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 

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