MVC Concepts Basics Model-View-Controller (MVC) Concepts for Web Developers SoftUni Team Technical Trainers Software University

Slides:



Advertisements
Similar presentations
1.  Understanding about How to Working with Server Side Scripting using PHP Framework (CodeIgniter) 2.
Advertisements

Software Quality Assurance QA Engineering, Testing, Bug Tracking, Test Automation Software University Technical Trainers SoftUni Team.
AngularJS Routing Routes, Route Parameters, Templates, Location, Navigation SoftUni Team Technical Trainers Software University
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
Software University Curriculum, Courses, Exams, Jobs SoftUni Team Technical Trainers Software University
PHP Basics Course Introduction SoftUni Team Technical Trainers Software University
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns
CAKEPHP Blog tutorial. what you’ll need examples/blog/blog.html 2  A running web server  A database server.
Composer packages Installing and Using Composer, Packagist, Packaging your code Mario Peshev Technical Trainer Software University
Consuming REST Services from C# SoftUni Team Technical Trainers Software University
MVC Advanced & Reflection Reflection, Parsing Dynamic Data, Asynchronous Requests SoftUni Team Technical Trainers Software University
Database APIs and Wrappers
Entity Framework Performance SoftUni Team Technical Trainers Software University
Microsoft Azure SoftUni Team Technical Trainers Software University
Svetlin Nakov Technical Trainer Software University
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC Angel Georgiev Part-time Trainer Software University
Trainers Team Ivan Yonkov Rated in the top 7% at Stack Overflow
Templating, Routing, lodash Extending functionality using Collections SoftUni Team Technical Trainers Software University
ASP.NET MVC Architecture Layouts, Filters, Sections, Helpers, Partial Views, Areas… SoftUni Team Technical Trainers Software University
Controllers and Markup Controllers, $scope, Markup, Directives, Expressions, Binding, Filters, Validation SoftUni Team Technical Trainers Software University.
AMD and RequireJS Splitting JavaScript Code into Dependent Modules Software University Technical Trainers SoftUni Team.
Using SQL Connecting, Retrieving Data, Executing SQL Commands, … Svetlin Nakov Technical Trainer Software University
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
Sessions and Cookies State Management, Cookies, Sessions, Hidden Fields SoftUni Team Technical Trainers Software University
Controls, Widgets, Grid…
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
AJAX in ASP.NET MVC AJAX, Partial Page Rendering, jQuery AJAX, MVC AJAX Helpers SoftUni Team Technical Trainers Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
ASP.NET SignalR SoftUni Team Technical Trainers Software University
Responsive Design Design that Adapts to Different Devices SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
ASP.NET Identity System
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
ORM Basics Repository Pattern, Models, Entity Manager Ivan Yonkov Technical Trainer Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
Software Technologies Course Overview SoftUni Team Technical Trainers Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
Web Storage and Cookies Cookies, Local and Session Storage SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Magento Basics Getting started developing for Magento
ASP.NET Essentials SoftUni Team ASP.NET MVC Introduction
Web API - Introduction AJAX, Spring Data REST SoftUni Team Web API
Introduction to MVC SoftUni Team Introduction to MVC
Deploying Web Application
Thymeleaf and Spring Controllers
PHP MVC Frameworks Course Introduction SoftUni Team Technical Trainers
PHP Fundamentals Course Introduction SoftUni Team Technical Trainers
What is Laravel ? By Georgi Genov.
ASP.NET Integration Testing
State Management Cookies, Sessions SoftUni Team State Management
PHP MVC Frameworks MVC Fundamentals SoftUni Team Technical Trainers
Spring Filters Spring Interceptors SoftUni Team Spring Interceptors
Registration, Login, Thymeleaf
MVC Architecture. Routing
Caching Data in ASP.NET MVC
The Right Way Control Flow
MVC Architecture, Symfony Framework for PHP Web Apps
AJAX and jQuery AJAX AJAX Concepts, XMLHttpRequest, jQuery AJAX: $.ajax(), $.get(), $.post() jQuery AJAX XMLHttpRequest SoftUni Team Technical Trainers.
C#: ASP.NET MVC Overview
Design & Module Development
Introduction to CodeIgniter (CI)
Extending functionality using Collections
ASP.NET Filters SoftUni Team ASP.NET MVC Introduction
Software Quality Assurance
Introduction to MVC PHP Web Development Ivan Yonkov Training Manager
JavaScript: ExpressJS Overview
Presentation transcript:

MVC Concepts Basics Model-View-Controller (MVC) Concepts for Web Developers SoftUni Team Technical Trainers Software University

Table of Contents 1.Typical Web App Structure 2.Typical PHP Apps Structure 3.MVC Concepts (Model-View-Controller)  Presentation  Logic  Data 4.Web Application Frameworks 5.Building Your Own MVC Framework 2

3 Typical Web App Structure and PHP Apps Presentation Business Logic Data Access Logic Web Browser Database Presentation Logic Views: HTML + PHP Business Logic Classes PHP Data Access Classes Web Browser MySQL PHP Controller Classes

4  MVC == Model-View-Controller  Views (presentation / UI)  Render UI (produce HTML)  Controllers (logic)  Prepare UI (presentation logic)  Update database (business logic)  Models (data)  Data access classes or ORM MVC Architecture for Web Apps

5  Web apps are typically built with a Web application framework  Build your own Web framework  More flexibility, takes more effort, needs more experience  Use some industrial Web framework  More mature, large community, more functionality, …  PHP: Laravel, Symfony, CodeIgniter, Yii, Phalcon, Zend, …LaravelSymfonyCodeIgniterYiiPhalconZend  C#: ASP.NET MVC, ASP.NET Web Forms, Nancy, …ASP.NET MVCASP.NET Web FormsNancy  Others: Rails (Ruby), Django (Python), Spring MVC (Java)RailsDjango Spring MVC Web Application Frameworks

6  Presentation in Web apps  Views and template engine – render dynamic HTML  PHP files for each view / partial view or based on a view engine  Presentation logic (prepare data for rendering)  PHP controllers: read data from DB, fill it in the view model  Page layout system (headers, footers, sidebars, etc.)  PHP fragments / layout templates  Notifications – show error / info messages  PHP framework logic + notifications partial view Web Frameworks: Presentation

7  Logic in Web applications  Controllers – process user actions (e.g. button click / form submit)  Presentation logic – prepare data (view models) for the UI  Business logic – do the business operations, e.g. post an article  CRUD operations – list / create / update / delete data  AJAX actions – render partial views or JSON result  Access control (user register, login, logout, admin area)  Session-based user tracking – login / logout / get current user Web Frameworks: Logic

8  Data in Web applications  Database access logic – execute DB operations  ORM approach – map classes to DB tables  Non-ORM approach – data access classes  Data validation – show errors for invalid form data  Data binding – auto map form data into objects  Data paging, sorting, filtering Web Frameworks: Data

Building a MVC Framework in PHP Basic Concepts

10  What is "front controller"?front controller  Architectural design pattern for Web applications  Front controller == centralized entry point for all requests Front Controller HTTP Request Controller Controller Controller View View View

11  Using.htaccess files in Apache.htaccess  Configures the access to the current folder and its subfolders  Rewriting URLs with mod_rewrite mod_rewrite  Route everything except /content/ and favicon.ico to index.php Rewriting URLs with.htaccess RewriteEngine On RewriteCond %{REQUEST_URI} !^/content/.*$ RewriteCond %{REQUEST_URI} !^/favicon\.ico$ RewriteRule ^ index.php.htaccess

12  Web applications hold many configurable application settings  Paths location of views, layouts, controllers, models, etc.  Database connection settings (DB host, username, password, …)  Other constants, e.g. page size, session timeout, …  Configuration settings in PHP – use define(…) or config class Configuration Settings define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASS', includes/config.php

13  Parse the request URI to extract the controller and action  Controller: " authors ". Action: " edit ". Parameters: [6]  Load class AuthorsControllers  Invoke function edit(6)  Default controller and default action  Controller: " home ". Action: " index ". Parameters: [] Implementing the Front Controller

14  Base controller  Holds the common controller logic  Holds the view model (view bag)  Render view / partial view  Redirect to another action  Current user / authorization  Add notification / error  Other common functionality Implementing the Controllers: BaseController BaseController Controller Controller ViewView inherit render ViewView

15 The Base Controller abstract class BaseController { public function __construct($controller, $action) { public function __construct($controller, $action) { $this->onInit(); $this->onInit(); } protected function onInit() { } // for overriding protected function onInit() { } // for overriding public function renderView($viewName = null) { public function renderView($viewName = null) { // Render layout header + the requested view + the footer // Render layout header + the requested view + the footer } protected function redirect( protected function redirect( $controller = null, $action = null, $params = []) { $controller = null, $action = null, $params = []) { header("Location: " …); die; header("Location: " …); die; }}controllers/BaseController.php

16 Implementing the Controllers class AuthorsController extends BaseController { extends BaseController { protected function onInit() { protected function onInit() { $this->title = 'Authors'; $this->title = 'Authors'; } public function index() { public function index() { $authorModel = new AuthorsModel(); $authorModel = new AuthorsModel(); $this->authors = $authorModel->getAll(); $this->authors = $authorModel->getAll(); } public function create() { … } public function create() { … } public function edit($id) { … } public function edit($id) { … } public function delete($id) { … } public function delete($id) { … }}controllers/AuthorsController.php Put a title in the view model Put a list of authors in the view model

17  Models holds the DB access logic  Can use some ORM (object-relational mapping) framework like Eloquent, Doctrine, Propel, DataMapper ORM, …Eloquent DoctrinePropelDataMapper ORM  Usually data model classes + framework for CRUD + queries  Simple frameworks just implement CRUD operations in DB access classes  BaseModel + classes inheriting from it Implementing the Models BaseModel Model Model inherit

18 Implementing the Base Model abstract class BaseModel { protected static $db; protected static $db; public function __construct() { public function __construct() { if (self::$db == null) { if (self::$db == null) { self::$db = new mysqli( self::$db = new mysqli( DB_HOST, DB_USER, DB_PASS, DB_NAME); DB_HOST, DB_USER, DB_PASS, DB_NAME); if (self::$db->connect_errno) { if (self::$db->connect_errno) { die('Cannot connect to database'); die('Cannot connect to database'); } } }}models/BaseModel.php

19 Implementing the Models class AuthorsModel extends BaseModel { public function getAll() { public function getAll() { $stmt = self::$db->query("SELECT * FROM authors"); $stmt = self::$db->query("SELECT * FROM authors"); return $stmt->fetch_all(MYSQLI_ASSOC); return $stmt->fetch_all(MYSQLI_ASSOC); } public function find($id) { public function find($id) { $stmt = self::$db->prepare("SELECT * FROM authors WHERE id = ?"); $stmt = self::$db->prepare("SELECT * FROM authors WHERE id = ?"); $stmt->bind_param("i", $id); $stmt->bind_param("i", $id); $stmt->execute(); $stmt->execute(); return $stmt->get_result()->fetch_assoc(); return $stmt->get_result()->fetch_assoc(); } public function create($name) { … } public function create($name) { … } public function edit($id, $name) { … } public function edit($id, $name) { … } public function delete($id) { … } public function delete($id) { … }}models/AuthorsModel.php

20  Views render the data from the view model (view bag)  Typically produces HTML fragment  Views can be based on pure PHP or on some view engine  Popular PHP view engines: Blade, Twig, …BladeTwig Implementing the Views {% for user in users %} * {{ user.name }} * {{ user.name }} {% else %} No user has been found. No user has been found. {% endfor %} users)) : ?> users)) : ?> users as $user) : ?> users as $user) : ?> No user has been found. No user has been found. Render with Twig Render with pure PHP

21 View Based on Pure PHP List of Authors List of Authors <table> ID Name Action ID Name Action authors as $author) : ?> authors as $author) : ?> ">[Edit] ">[Edit] ">[Delete] ">[Delete] </table> [Create New] [Create New] views/authors/index.php

22  The page layout system in Web apps  Avoids repeating headers, footers, sidebars and others  Simple implementations  Just include header.php and footer.php  More-complex solutions  Multiple layouts with inheritance  Components (partial views), parameters Layout System

Building a MVC Framework in PHP Live Demo

? ? ? ? ? ? ? ? ? MVC Concepts Basics

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 25

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg