Folien

Werbung
Web Technologien –
Model View Controller Pattern
(MVC)
Univ.-Prof. Dr.-Ing. Wolfgang Maass
Chair in Information and Service Systems
Department of Law and Economics
WS 2011/2012
Wednesdays, 8:00 – 10:00 a.m.
Room HS 021, B4 1
•  Das Datenbanksystem MySQL
ermöglicht die strukturierte und
persistente Speicherung von Daten
•  Die Skriptsprache PHP ermöglicht
die Erstellung komplexer
Serverskripte, z.B. mit Zugriff auf
das MySQL DBMS zur Datenhaltung
17.11.11
Univ.-Prof. Dr.-Ing. Wolfgang Maass
Server
•  Der Linux, Apache, MySQL, PHP
Stack (= LAMP) ist eine Sammlung
von Open Source Standardsoftware
zur Realisierung serverseitiger
dynamischer Websites
Client
Wrap-Up
Browser
PHP
Apache
, (Python, Perl)
MySQL
Linux
Slide 2
Komplexe Softwaresysteme
Probleme bei der Entwicklung komplexer Softwaresysteme:
•  In Teams vom mehreren Personen geht der Gesamtüberblick schnell
verloren, jeder einzelne Entwickler kennt sich nur in seinem
Quellcode aus
•  Funktionalität wird doppelt entwickelt und Insellösungen entstehen
•  Fehler im System können nur schwer gefunden werden
•  Eine Anpassung und Erweiterung der Funktionalität durch andere ist
kaum möglich
Angestrebte Ziele aus dem Softwareengineering:
•  Kapselung von Einzelaufgaben
•  Wiederverwendbarkeit von Quellcode
•  Stabilität und Überprüfbarkeit
•  Klar verständliche und einfache Strukturierung
17.11.11
Univ.-Prof. Dr.-Ing. Wolfgang Maass
Slide 3
Entwurfsmuster
•  Entwurfsmuster (engl. design patterns) sind Lösungsansätze
für wiederkehrende Probleme bei der Softwareentwicklung
•  Sie unterstützen Softwarearchitekten und Programmierer bei
der Strukturierung von Softwarearchitekturen in
Komponenten
•  Die Wiederverwendung von Komponenten stellt die
Wiederverwendung von ausgereiftem Quellcode sicher
Beispiel: Asynchrone Methodenaufrufe
Angewendet bei AJAX um die Website nicht zu blockieren,
während im Hintergrund komplexe Anfragen auf Serverskripte
laufen können
17.11.11
Univ.-Prof. Dr.-Ing. Wolfgang Maass
Slide 4
Model View Controller (MVC)
Klassisches Entwurfsmuster zur Strukturierung von
Softwarearchitekturen in drei Einheiten:
•  Datenmodell (engl. model)
•  Präsentation (engl. view)
•  Steuerung (engl. controller)
Vorteile:
•  Auf jeder Ebene wird muss nur ein Aufgabenbereich der Anwendung im
Detail bearbeitet werden
•  Jede Ebene kann unabhängig von den beiden anderen getestet werden
•  Jede Ebene kann unabhängig von den beiden anderen ausgetauscht
werden
17.11.11
Univ.-Prof. Dr.-Ing. Wolfgang Maass
Slide 5
Einheiten des MVC Pattern
•  Datenmodell:
Enthält die für die jeweilige Anwendung notwendigen
Datenmodelle zur Speicherung der Anwendungsdaten, sowie
die zur Speicherung gehörige Geschäftslogik
•  Präsentation:
Enthält die Funktionalität zur Darstellung der Daten auf dem
Benutzerinterface, sowie zur Weiterleitung der
Benutzerinteraktionen an die Steuerung
•  Steuerung:
Enthält die Funktionalität zur Ausführung der
Benutzerinterakationen auf das Datenmodell, sowie zur
Anpassung der Präsentation gemäß der Benutzerinteraktion
17.11.11
Univ.-Prof. Dr.-Ing. Wolfgang Maass
Slide 6
Exemplarischer Ablauf
Exemplarischer Ablauf des MVC Pattern im LAMP Stack bei der
Erstellung eines Kommentar-Eintrages:
1. Ein Besucher
sendet einen
Kommentar-Eintrag
mittels WebFormular an den
Server
4b. Bei einer
klassischen
Webanwendung
lässt der Controller
die neue, passende
Website mit dem
integrierten
Kommentareintrag
erzeugen
17.11.11
2. Die Anfrage wird an das
passende Steuerungsmodul
übergeben
3. Mittels der Geschäftslogik im
Modell wird der neue Eintrag
gespeichert
4a. Sofern es sich um eine AJAXAnwendung handelt informiert das
Modell die Präsentation über eine
Datenänderung
Univ.-Prof. Dr.-Ing. Wolfgang Maass
Slide 7
LAMP/PHP MVC Frameworks
LAMP/PHP MVC Frameworks liefern einen umfangreichen Baukasten
zum Einsatz von MVC und anderen Entwurfsmustern für Rich Internet
Applications (RIA)
•  Nachteile:
•  Der Entwickler muss den Konventionen des Frameworks folgen
•  Der Entwickler muss die unterstützenden Abläufe des MVC Frameworks
verstehen und einzusetzen wissen
•  Vorteile:
•  Schnellere, robustere und sicherere Entwicklung von RIAs
•  Wenig Programmieraufwand und schnelle Erfolge
•  Einfachere Erweiterbarkeit um neue Funktionen
Ø  „Convention over configuration“ bzw. „coding by convention“
17.11.11
Univ.-Prof. Dr.-Ing. Wolfgang Maass
Slide 8
LAMP/PHP MVC Frameworks
CakePHP
Downloads
Documentation
Community
Services
You are browsing the website for symfony 1. Click here to visit the new website for Symfony2
About
Installation
Documentation
Plugins
Community
Blog
Development
Open-Source PHP Web Framework
CakePHP enables PHP users at all levels to
rapidly develop robust web applications.
Symfony is a full-stack framework, a library of cohesive
classes written in PHP.
Getting Started
It provides an architecture, components and tools for developers to
build complex web applications faster. Choosing symfony allows you
to release your applications earlier, host and scale them without
problem, and maintain them over time with no surprise.
Symfony is based on experience. It does not reinvent the wheel: it
uses most of the best practices of web development and integrates
some great third-party libraries.
ABOUT
DOWNLOADS
DOCUMENTATION
COMMUNITY
New users join the community every day, and that makes of
symfony the most
PHP framework
around. Adevelopment
large
about popular
downloads
documentation
community means easy-to-find support, user-contributed
documentation, plugins, and free applications.
Extra Hot: Release 2.0.3 Stable & 1.3.13
Get it now!
Hot Features
Learn
Interact
The Fast, Secure and Professional
PHP Framework
Read
2.0.3 Stable
Yii comes with rich features: MVC, DAO/ActiveRecord, I18N/L10N,
ten scaffolding,
caching, authentication and role-basedWatch
access the
control,
minutes
testing, etc. It can reduce your development
time screencast
significantly. of
the ajax tutorial or
test it online
read the announcement
view the changelog
download: 1.3.13 Stable
Zend Framework 2.0.0beta1 Released!
Zend Framework 2.0.0beta1 Released!
Zend Framework 2.0.0beta1 Released!
Zend Framework 1.11.11 Released
Announcing September's Zend
Announcing September's Zend
Framework Bug Hunt Days
Framework Bug Hunt Days
Why ZF?
QuickStart
Contributors Guide
You've got questions, we've got
solutions
Take our 30-minute tour
Contributing is easier than you
think
Case Studies
From Fortune 500s to startups
Yii only loads the features that you need. It has
powerful caching support. It is explicitly designed to
work efficiently with AJAX.
More than 500 examples in 6Home
Blog
Packages
The ultimate
communal
knowledge base
Discover
Let us help you perfect your ZF
Solar is a PHP 5 framework for
skills
web application development.
It is fully name-spaced and
uses enterprise application
design patterns, with built-in
support for localization and
configuration at all levels.
Read more about Solar...
Professional
Security comes as standard with Yii. It includes
input validation, output filtering, SQL injection and
Cross-site scripting prevention.
Huge potential returns from renewable
energy investments
TheEcoAlliance.org/solar
A picture sharing platform.
"Share, Enjoy & Remember Life Better"
Community Wiki
Project
Download Yii
1.4 branch: 1.4.15
2.0 branch: 2.0.0
Master symfony
Be trained by SensioLabs experts (2
to 6 day sessions -- French or
English).
trainings.sensiolabs.com
Books on symfony
Learn more about symfony with the
official guides.
books.sensiolabs.com
L'audit Qualité par
SensioLabs
200 points de contrôle de votre
applicatif web.
audit.sensiolabs.com
Search
search
powered by google
Be trained by symfony experts
Nov 14: Paris
(Getting Started with
Symfony2 - Français)
Nov 21: Paris
(Extending & Hacking
Symfony2 - Français)
Nov 21: Köln
(Mastering Symfony2 -
Deutsch)
Nov 24: Köln
(Getting Started with
Symfony2 - Deutsch)
Yii helps you develop clean and reusable code. It
follows the MVC pattern, ensuring a clear
separation of logic and presentation.
Investing in Solar Power
Testimonials
Help us deal with our issues
Reference Guide
FAQ | Sitemap | Wiki | Issue Tracker | Code Browser | License | Changelog |
Secure
Issue Tracker
Your topics on your time
Training
Take the Tour
This screencast shows
The Jobeet website is
In addition to tutorials
Or dive directly into Yii with
v1.1.8 released on Jun 26, 2011
the best PHP code
a real-world web app,
and showcase apps,
screencasts or guide
Release notes · License (BSD)
generation engine for
developed entirely in
symfony has an
your backend
symfony. Step by
extensive
interfaces.
step, this is how.
documentation. Dive
in.
PicLyf
Multimedia
languages
Fast
community
1. You create the database;
2. Yii generates the base PHP code;
3. You customize the code to fit your exact needs.
Yii is a high-performance PHP framework best for
developing Web 2.0 applications.
download: 1.2.11 Stable
Discuss on our mailinglists, and join us in the
#symfony IRC channel.
Three steps to build your application rapidly:
1.3k
Get it now!
CakePHP is a rapid development
framework for PHP that provides an
extensible architecture for developing,
maintaining, and deploying
applications. Using commonly known
design patterns like MVC and ORM
within the convention over
configuration paradigm, CakePHP
Learn the framework
with the Practical
symfony book.
Thousands of developers already trust symfony for their
demos · guide · class reference · wiki · extensions · forum · live chat · login
applications!
Search the entire site
SERVICES
Discover symfony with
the Get Started tutorial.
Classes
Download
Download the latest release
and start using it now, or read
the installation instructions.
Manual
Wiki
“
Explore
Bugs
Latest News
AUG 25, 2011
Yii 1.1 Application Development Cookbook released
PACKT publishing released the second book about Yii
authored by core team member Alexander Makarov
(samdark). This book is a recipe book about Yii. It contains
13 indepen​dent chapters full of material that will show you
how to use Yii efficiently.
Read more »
Yii is a simple but very powerful application framework with a very
Discuss
Try getting started.
Examine the list of
packages.
Review or report bugs and
requests.
Join a Solar mailing list.
Consult the class API
reference.
Contribute to the
community wiki.
View the source code.
Read more about Solar...
system version 1.1.2 stable as of
2010-11-09
© 2006 - 2011 by Zend Technologies Ltd. All rights reserved.
Roadmap | CLA | Security | Contact Us
Copyright © 2005-2011, Paul M. Jones and other contributors.
Logo Design by Ben Carter, Site Design by Matt Brett.
17.11.11
Univ.-Prof. Dr.-Ing. Wolfgang Maass
Slide 9
MVC mit Solar PHP
Einsatz eines MVC Framework in der Praxis am Beispiel von
Solar 1.1.2:
Funktionsumfang und Vorteile:
•  Basiert auf Entwurfsmustern, bspw. MVC
•  Unterstützung der Komponentenidee über Namensräume
•  Vererbte Konfigurationen und Lokalisierung
•  PHP5-Datenmodell mit Datenbankanbindung und Schutz
gegen SQL-Angriffe
•  Sehr einfache Installation
und niedrige Einstiegshürde
•  uvm.
17.11.11
Univ.-Prof. Dr.-Ing. Wolfgang Maass
Slide 10
Solar Komponentisierung
•  Grundlage jeder RIA in Solar ist das Anlegen eines
Vendor Space und mindestens einer dazu gehörigen App
•  Der Vendor Space enthalt alle projektrelevanten Dateien und
kann zzgl. App über das „solar“-Skript erzeugt werden:
htdocs/solar> ./script/solar make-vendor Me
htdocs/solar> ./script/solar make-app Me_App_Blog"
•  Externe Bibliotheken können eingebunden werden indem man
ihre Spaces ebenfalls ins Solar-Verzeichnis „source“ kopiert
•  Nach der Installation befinden sich im Verzeichnis „source“
lediglich die Bibliotheken des Vendor „Solar“
17.11.11
Univ.-Prof. Dr.-Ing. Wolfgang Maass
Slide 11
Solar Verzeichniskonventionen
Das „solar“-Skript erzeugt für jeden Vendor die gleiche
Verzeichnisstruktur, welche nach den Konventionen
Verzeichnisse für
• 
• 
• 
• 
• 
• 
das Datenmodell,
die Steuerungsklassen,
Präsentationshelfer,
sowie Hilfsklassen,
Dokumentationen und
Testfälle etc. enthält
Detaillierte Informationen sind
im Handbuch zu finden:
http://solarphp.com/manual/
17.11.11
Linux Kommandozeile
htdocs/solar> find ./source/me/ -maxdepth 2 -type d
./source/me/
./source/me/docs
./source/me/tests
./source/me/tests/Fixture
./source/me/tests/Mock
./source/me/tests/Test
./source/me/script
./source/me/config
./source/me/Me
./source/me/Me/Model
./source/me/Me/Cli
./source/me/Me/Sql
./source/me/Me/Controller
Univ.-Prof. Dr.-Ing. Wolfgang Maass
Slide 12
Solar Konfiguration
htdocs/solar/config.php
Bereits wenige Anpassungen der
Standardkonfiguration konfigurieren
die eigene RIA:
•  Eintragen der eigenen App in den Front
Controller Stack (Präsentation)
•  Eintragen der eigenen Datenmodelle in
den Model Catalog (Datenmodell)
•  Angeben der Datenbankkonfiguration, z.B.
der MySQL Datenbank
17.11.11
Univ.-Prof. Dr.-Ing. Wolfgang Maass
<?php
// front controller
$config['Solar_Controller_Front'] =
array('classes' => array('Me_App',
'Solar_App'),
[...] 'explain' => true);
[...]
// model catalog
$config['Solar_Sql_Model_Catalog']
['classes'] = array('Me_Model');
[...]
// SQL adapter
$config['Solar_Sql']['adapter'] =
'Solar_Sql_Adapter_Mysql‘;
$config['Solar_Sql_Adapter_Mysql'] =
array('host' => 'localhost',
'name' => 'Blog', 'user' => 'php',
'pass' => 'abc');
?>
Slide 13
MVC Model: Datenmodelle in Solar
•  Mittels des „solar“-Skript kann ein zuvor
erstelltes Datenbankmodell Tabelle für
Tabelle in Solar überführt werden:
htdocs/solar>
./script/solar make-model ISS_Model_Blogs"
•  Bei diesem Vorgang werden automatisch die Restriktionen der
Datenbank (NOT NULL etc.) sowie die Datentypen (INT etc.)
berücksichtigt und PHP-Klassen für das Datenmodell erzeugt
•  Diese Klassen können im weiteren bspw. mit Filtern erweitert
werden, z.B. dass ein Blogeintrag bei der Erstellung den Status
unveröffentlicht hat.
17.11.11
Univ.-Prof. Dr.-Ing. Wolfgang Maass
Slide 14
MVC Model:
Datensätze in Solar verwalten
Über den Model Catalog kann im Sinne der PHP Klassenlogik
auf das persistente Datenmodell zugegriffen werden:
protected $_model;"
$this->_model = Solar_Registry::get('model_catalog');"
"
Für alle CRUD-Funktionen stehen Funktionen parat:
$this->item = $this->_model->blogs->fetch($id); //
$this->item = $this->_model->blogs->fetchNew(); //
$this->item->title = 'My new blog post'; // Access
"
$data = $this->_request->post('blog'); // Get data
$this->item->load($data); // Form data to entry"
$this->item->save(); // Save entry"
"
$this->item->delete(); // Delete entry"
17.11.11
Univ.-Prof. Dr.-Ing. Wolfgang Maass
Existing entry OR"
New entry"
columns"
from HTML form"
Slide 15
MVC Controller:
Aktionssteuerung in Solar
•  Die Steuerung einer App ist immer
im Verzeichnis source/vendor/
Vendor/App/NameDerApp.php zu
finden.
•  Wird keine Aktion angegeben wird
automatisch die Aktion „index“
ausgeführt, welche als PHP
Funktion actionIndex() anlegt ist
•  Neue Aktionen können angelegt
werden indem man lediglich die
entsprechende Funktion anlegt
17.11.11
Univ.-Prof. Dr.-Ing. Wolfgang Maass
htdocs/solar/source/me/Me/App/Blog.php
[...]
public function actionIndex() {
// filtered blog articles
$fetch = array(
'where' =>
array('blogs.status = ?' => 'public'),
'order' => 'blogs.created DESC',
'page' => 'all‘);
// fetch all matching records
$this->list = $this->_model->
blogs->fetchAll($fetch);
}
public function actionEdit() {
[...]
}
Slide 16
MVC Views: Präsentation in Solar
•  Sobald ein Präsentationsskript
zu einer Aktion existiert wird
selbiges automatisch mit den
bezogenen Daten ausgeführt
•  Nach dem Präsentationsskript
wird im Verzeichnis source/
vendor/Vendor/App/
NameDerApp/View gesucht
•  Zur Internationalisierung
werden Strings nur über ihre
Bezeichner referenziert und
extern befüllt
•  Das Framework stellt
bestimmte Variablen und
Funktionen automatisch bereit
17.11.11
htdocs/solar/source/me/Me/App/Blog/View/index.php
<?php
echo $this->getText('TEXT_WELCOME');
?>
<p>
<?php foreach ($this->list as $item): ?>
<li><?php
echo $this->escape($item->title);
echo " ";
echo $this->
action("{$this->controller}/read/{$item->id}",
'ACTION_READ');?>
</li>
<?php endforeach; ?>
</p>
Univ.-Prof. Dr.-Ing. Wolfgang Maass
Slide 17
MVC Controller: URLs in Solar
Die Vermittlung zwischen verschiedenen Steuerungsmodulen und
Aktionen erfolgt direkt über die URL des jeweiligen Aufrufs:
http://localhost/index.php/blog/edit/3"
"
class Me_App_Blog extends Me_Controller_Page{"
public function actionEdit($id = null) { [...] }"
}"
Über PHP kann der Nutzer ebenfalls auf andere Steuerungsmodule und
Aktionen umgeleitet werden:
if ($this->item->save()) {"
$uri = "/{$this->_controller}/edit/{$this->item->id}";"
return $this->_redirectNoCache($uri);"
}"
17.11.11
Univ.-Prof. Dr.-Ing. Wolfgang Maass
Slide 18
Komplette Blog-App in Solar
17.11.11
Univ.-Prof. Dr.-Ing. Wolfgang Maass
Slide 19
Literatur
Bücher:
•  Eric Freeman, Elisabeth Freeman, Kathy Sierra, Bert Bates
Entwurfsmuster von Kopf bis Fuß
ISBN-10: 3897214210, ISBN-13: 978-3897214217
•  Erich Gamma, Richard Helm, Ralph E. Johnson, John Vlissides
Entwurfsmuster. Elemente wiederverwendbarer objektorientierter
Software, Addison Wesley, München 2004
ISBN-10: 3827321999
Web:
•  http://solarphp.com/
•  http://www.php.net/
•  http://oreilly.com/php/archive/mvc-intro.html
17.11.11
Univ.-Prof. Dr.-Ing. Wolfgang Maass
Slide 20
Univ.-Prof. Dr.-Ing. Wolfgang Maass
Chair in Information and Service Systems
Saarland University, Germany
Univ.-Prof. Dr.-Ing. Wolfgang Maass
Herunterladen