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)

Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
Asp.net MVC training session
Asp.net MVC training sessionAsp.net MVC training session
Asp.net MVC training session
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
ASP.NET MVC.
ASP.NET MVC.ASP.NET MVC.
ASP.NET MVC.
 
jQuery Ajax
jQuery AjaxjQuery Ajax
jQuery Ajax
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
 
GET and POST in PHP
GET and POST in PHPGET and POST in PHP
GET and POST in PHP
 
ASP .net MVC
ASP .net MVCASP .net MVC
ASP .net MVC
 
jQuery
jQueryjQuery
jQuery
 
Ajax and Jquery
Ajax and JqueryAjax and Jquery
Ajax and Jquery
 
ASP.NET Lecture 1
ASP.NET Lecture 1ASP.NET Lecture 1
ASP.NET Lecture 1
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
ASP.NET - Life cycle of asp
ASP.NET - Life cycle of aspASP.NET - Life cycle of asp
ASP.NET - Life cycle of asp
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Arquitetura Node com NestJS
Arquitetura Node com NestJSArquitetura Node com NestJS
Arquitetura Node com NestJS
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with Overview
 

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

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Recently uploaded (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

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