Model-View-Controller

Slides:



Advertisements
Similar presentations
The Librarian Web Page Carol Wolf CS396X. Create new controller  To create a new controller that can manage more than just books, type ruby script/generate.
Advertisements

Ruby on Rails Model of MVC. Model-View-Controller Paradigm A way of organizing a software system Benefits: Isolation of business logic from the user interface.
Chapter 15 © 2010 by Addison Wesley Longman, Inc Origins and Uses of Ruby - Designed by Yukihiro Matsumoto; released in Use spread rapidly.
Ruby on Rails by Manik Juneja Ruby On Rails. Ruby on Rails by Manik Juneja Rails is a Web Application development framework. Based on the MVC pattern.
ExtJS 4.0 JavaScript MVC Framework. Who ExtJS is provided by Sencha ( o Sencha Touch o GWT o CSS Animator o IO (Cloud Data Management)
Software Architecture Patterns (2). what is architecture? (recap) o an overall blueprint/model describing the structures and properties of a "system"
Associations: Mechanics (ESaaS §5.3) © 2013 Armando Fox & David Patterson, all rights reserved.
Application Architectures Vijayan Sugumaran Department of DIS Oakland University.
Computer Science 101 Web Access to Databases Overview of Web Access to Databases.
Web Application Architecture: multi-tier (2-tier, 3-tier) & mvc
CS 169 Software Engineering SaaS Architecture Armando Fox, David Patterson, and Koushik Sen Spring
Christopher M. Pascucci Basic Structural Concepts of.NET Browser – Server Interaction.
UNIT-V The MVC architecture and Struts Framework.
What is Software Architecture?
Sys Prog & Scripting - HW Univ1 Systems Programming & Scripting Lecture 15: PHP Introduction.
A little engineering on Rails Robert W. Hasker. Goals Intro to the Rails framework ▫Basic concepts: MVC, Active Record ▫A bit of Ruby Using Rails to build.
RUBY ON RAILS Mark Zhang. In this talk  Overview of Ruby on Rails  Core ideas  Show a tiny bit of example code  Touch on several general web development/
Ruby on Rails. What is Ruby on Rails? Ruby on Rails is an open source full-stack web framework. It is an alternative to PHP/MySQL. It can render templates,
Ruby on Rails CSCI 6314 David Gaspar Jennifer Garcia Avila.
INTRODUCTION TO WEB DATABASE PROGRAMMING
J2EE Web Fundamentals Lesson 1 Introduction and Overview
Rails and Grails. To get started Make sure you have java installed You can get the sdk and jre at:
Database System Concepts and Architecture Lecture # 3 22 June 2012 National University of Computer and Emerging Sciences.
UC Berkeley Hello Rails. Review: MVC Goal: separate organization of data (model) from UI & presentation (view) by introducing controller –mediates user.
Web Application Architecture and Communication. Displaying a Web page in a Browser
Copyright © cs-tutorial.com. Introduction to Web Development In 1990 and 1991,Tim Berners-Lee created the World Wide Web at the European Laboratory for.
Web Application Programming Carol Wolf Computer Science.
Web Architecture & Services (2) Representational State Transfer (REST)
REST.  REST is an acronym standing for Representational State Transfer  A software architecture style for building scalable web services  Typically,
MVC & ActiveRecord by Christian Mohr & Mohamed Souiai.
® IBM Software Group © 2007 IBM Corporation J2EE Web Component Introduction
Lecture 10 Rails Projects Topics SaaSSaaS Readings: SaaS book Ch 2, 4 February 24, 2014 CSCE 740 Software Engineering.
CODD’s 12 RULES OF RELATIONAL DATABASE
HNDComputing – DeMontfort University  DeMontfort University 2011 Database Fundamentals wk2 Database Design ConceptsDatabase Design Concepts Database Design.
1 Dr Alexiei Dingli Web Science Stream Introducing Rails.
1 Another group of Patterns Architectural Patterns.
Ruby on Rails Your first app. Rails files app/ Contains the controllers, models, views and assets for your application. You’ll focus on this folder for.
Lecture 11 Rails Topics SaaSSaaS Readings: SaaS book Ch February CSCE 740 Software Engineering.
The Active Record Paradigm Databases in Database-Centric Web Site Development.
Chapter 6 Server-side Programming: Java Servlets
REST - Introduction Based on material from InfoQ.com (Stefan Tilkov) And slides from MindTouch.com (Steve Bjorg) 1.
Architectural Patterns Support Lecture. Software Architecture l Architecture is OVERLOADED System architecture Application architecture l Architecture.
INTRODUCTION TO WEB APPLICATION Chapter 1. In this chapter, you will learn about:  The evolution of the Internet  The beginning of the World Wide Web,
Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the.
RUBY ON RAILS (RoR) Ishwor Khadka. Why Ruby on Rails?
Lecture 13b Rails – Controllers and Views Topics SaaSSaaS Readings: SaaS book Ch March 3, 2014 CSCE 740 Software Engineering.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
CS 4720 Model-View-Controller CS 4720 – Web & Mobile Systems.
1 Copyright © 2004, Oracle. All rights reserved. Oracle Application Development Framework.
Web Services An Introduction Copyright © Curt Hill.
SEA Side – Extreme Programming 1 SEA Side Software Engineering Annotations Architectural Patterns Professor Sara Stoecklin Director of Software Engineering-
Rails and routing INFO 2310: Topics in Web Design and Programming.
CS 160 and CMPE/SE 131 Software Engineering February 9 Class Meeting Department of Computer Science Department of Computer Engineering San José State University.
Ruby on Rails. Web Framework for Ruby Designed to make it easier to develop, deploy, and maintain web applications Design with Model-View-Controller –almost.
Lecture 12 Rails 169 Review Slides Topics SaaSSaaS Readings: SaaS book Ch February CSCE 740 Software Engineering.
Routes Carol Wolf Computer Science. RESTful Architecture  Rails uses REST-style architecture: representation state transfer  resources :courses in routes.rb.
National College of Science & Information Technology.
Chapter 1 Getting Started with ASP.NET Objectives Why ASP? To get familiar with our IDE (Integrated Development Environment ), Visual Studio. Understand.
MVC Architecture, Symfony Framework for PHP Web Apps
Web Software Model CS 4640 Programming Languages for Web Applications
CMPE 280 Web UI Design and Development October 24 Class Meeting
Ruby on Rails by Manik Juneja
Ruby on Rails by Manik Juneja
Lecture 1: Multi-tier Architecture Overview
Architecture Philip Ritchey slides generously gifted by Jeff Huang.
REST APIs Maxwell Furman Department of MIS Fox School of Business
Database Management Systems
Back end Development CS Programming Languages for Web Applications
Back end Development CS Programming Languages for Web Applications
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Model-View-Controller Engineering Software as a Service §2.5 earliest ever lecture prep! aug 4 follow along download slides © 2013 Armando Fox & David Patterson, all rights reserved

Whither Frameworks? Is there common application structure… in interactive user-facing apps… …that could simplify app development if we captured them in a framework?

Chapter 2 Overview

The MVC Design Pattern View Model Goal: separate organization of data (model) from UI & presentation (view) by introducing controller mediates user actions requesting access to data presents data for rendering by the view Web apps may seem “obviously” MVC by design, but other alternatives are possible... • User actions • Directives for rendering data • Read data • Update data • Data provided to views through controller Controller Model View

Each Entity Has a Model, Controller, & Set of Views Movies Controller Movie Moviegoers Controller Moviegoer Reviews Controller Review

Alternatives to MVC A B C Page Controller (Ruby Sinatra) page A A page B page C B C models Front Controller (J2EE servlet) app models views Template View (PHP) models views Rails supports SaaS apps structured as MVC, but other architectures may be better fit for some apps.

END

Which statement is NOT true about the Model-View-Controller (MVC) architectural pattern: In SaaS apps on the Web, controller actions and view contents are transmitted using HTTP. ☐ All MVC apps have both a “client” part (e.g. Web browser) and a “cloud” part (e.g. Rails app on cloud). ☐ Model-View-Controller is just one of several possible ways to structure a SaaS app. ☐ True. False. An MVC app could all be running on same machine. True. Peers can each have MVC pattern, peers access each other via view. Peer-to-peer apps (vs. client-server apps) can be structured as Model-View-Controller. ☐

END

Models, Databases, and Active Record Engineering Software as a Service §2.6 earliest ever lecture prep! aug 4 follow along download slides © 2013 Armando Fox & David Patterson, all rights reserved

Data Storage How should we store and retrieve record-oriented structured data? What is the relationship between data as stored and data as manipulated in a programming language?

Chapter 2 Overview

In-Memory vs. In-Storage Objects #<Movie:0x1295580> m.name, m.rating, ... marshal/serialize ? #<Movie:0x32ffe416> m.name, m.rating, ... unmarshal/deserialize How to represent persisted object in storage Example: Movie with name & rating attributes Basic operations on object: CRUD (Create, Read, Update, Delete) ActiveRecord: every model knows how to CRUD itself, using common mechanisms

Rails Models Store Data in Relational Databases (RDBMS) Each type of model gets its own database table All rows in table have identical structure one row in table == one instance of model’s class Each column stores value of an attribute of the model Each row has unique value for primary key (by convention, in Rails this is an integer and is called id) Schema: Collection of all tables and their structure id rating title release_date 2 G Gone With the Wind 1939-12-15 11 PG Casablanca 1942-11-26 ... 35 Star Wars 1977-05-25

Alternative: DataMapper Data Mapper associates separate mapper with each model Idea: keep mapping independent of particular data store used => works with more types of databases Used by Google AppEngine Con: can’t exploit RDBMS features to simplify complex queries & relationships We’ll revisit when talking about associations

END

Which statement is not true about the Model in Model-View-Controller: The CRUD actions only apply to models backed by a database that supports ActiveRecord. ☐ Part of the Model’s job is to convert between in-memory and stored representations of objects. ☐ Although Model data is displayed by the View, a Models’ direct interaction is with Controllers. ☐ False. CRUD applies to all data models. True. Although DataMapper doesn’t use relational databases, it’s a valid way to implement a Model. ☐

END

Administrivia Who Is Not On a Project Team? Which Teams Do Not Have 5-6 Members? Quiz 1 Thu 2/5 Covers Chapters 1 and 2 15 minutes, starts exactly at start of class!

END

Controllers, Routes, and RESTfulness Engineering Software as a Service §2.7 earliest ever lecture prep! aug 4 follow along download slides © 2013 Armando Fox & David Patterson, all rights reserved

Design for SOA What design decisions would allow our app to support Service-Oriented Architecture?

Chapter 2 Overview

REST (Representational State Transfer) - R. Fielding, 2000 Idea: URI names resource, not page or action Self-contained: which resource, and what to do to it Responses include hyperlinks to discover additional RESTful resources “a post hoc [after the fact] description of the features that made the Web successful” A service (in the SOA sense) whose operations are like this is a RESTful service Ideally, RESTful URIs name the operations

Routes In MVC, each interaction the user can do is handled by a controller action Ruby method that handles that interaction A route maps <HTTP method, URI> to controller action Route Action GET /movies/3 Show info about movie whose ID=3 POST /movies Create new movie from attached form data PUT /movies/5 Update movie ID 5 from attached form data DELETE /movies/5 Delete movie whose ID=5

Brief Intro to Rails’ Routing Subsystem dispatch <method,URI> to correct controller action provides helper methods that generate a <method,URI> pair given a controller action parses query parameters from both URI and form submission into a convenient hash Built-in shortcuts to generate all CRUD routes (though most apps will also have other routes) Most apps will have routes Rake is Ruby make command I GET /movies {:action=>"index", :controller=>"movies"} C POST /movies {:action=>"create", :controller=>"movies"} GET /movies/new {:action=>"new", :controller=>"movies"} GET /movies/:id/edit {:action=>"edit", :controller=>"movies"} R GET /movies/:id {:action=>"show", :controller=>"movies"} U PUT /movies/:id {:action=>"update", :controller=>"movies"} D DELETE /movies/:id {:action=>"destroy", :controller=>"movies"} rake routes

GET /movies/3/edit HTTP/1.0 Matches route: GET /movies/:id/edit {:action=>"edit", :controller=>"movies"} Parse wildcard parameters: params[:id] = "3" Dispatch to edit method in movies_controller.rb To include a URI in generated view that will submit the form to the update controller action with params[:id]==3, call helper: update_movie_path(3) # => PUT /movies/3 I GET /movies {:action=>"index", :controller=>"movies"} C POST /movies {:action=>"create", :controller=>"movies"} GET /movies/new {:action=>"new", :controller=>"movies"} GET /movies/:id/edit {:action=>"edit", :controller=>"movies"} R GET /movies/:id {:action=>"show", :controller=>"movies"} U PUT /movies/:id {:action=>"update", :controller=>"movies"} D DELETE /movies/:id {:action=>"destroy", :controller=>"movies"} rake routes

END

Which statement is NOT true regarding Rails RESTful routes and the resources to which they refer: A resource may be existing content or a request to modify something. ☐ In an MVC app, every route must eventually trigger a controller action. ☐ One common set of RESTful actions is the CRUD actions on models. ☐ True. False. Example: “GET /movies” The route always contains one or more "wildcard" parameters, such as :id, to identify the particular resource instance in the operation ☐

END

Template Views and Haml Engineering Software as a Service §2.8 © 2013 Armando Fox & David Patterson, all rights reserved

HTML Generation HTML is how we must present content to browsers… …but what is the process by which our app’s output becomes HTML?

Chapter 2 Overview

Template View Pattern View consists of markup with selected interpolation to happen at runtime Usually, values of variables or result of evaluating short bits of code In the past, this was the app (e.g. PHP) Alternative: Transform View Closure XML Haml Closure Renderer (Action-View) Renderer (Action-View) HTML JSON Movie erb

Haml is HTML on a Diet %h1.pagename All Movies %table#movies %thead %tr %th Movie Title %th Release Date %th More Info %tbody - @movies.each do |movie| %td= movie.title %td= movie.release_date %td= link_to "More on #{movie.title}", | movie_path(movie) | = link_to 'Add new movie', new_movie_path no open/close tags: use indentation tag entirely on single line, or use indentation to indicate nesting how to specify ID & class code that is executed but NOT substituted note lack of 'end' for 'do': implied by indentation code that is executed and substituted multi-line – deliberately awkward

Don’t Put Code in Your Views Syntactically, you can put any code in view But MVC advocates thin views & controllers Haml makes deliberately awkward to put in lots of code Helpers (methods that “prettify” objects for including in views) have their own place in Rails app Alternative to Haml: html.erb (Embedded Ruby) templates, look more like PHP

END

It will work, but it’s bad form and violates the MVC guidelines What happens if you embed code in your Rails views that tries to directly access the model (in the database)? It will work, but it’s bad form and violates the MVC guidelines ☐ It will work when developing against a “toy” database, but not in production ☐ It won’t work, because Views can’t communicate directly with Models ☐ False. True. Routes will only specify the controller and action (method) in that controller. Behavior varies depending on the app ☐

END

© 2013 Armando Fox & David Patterson, all rights reserved Summary & Reflections: SaaS Architecture (Engineering Software as a Service §2.9-2.10) earliest ever lecture prep! aug 4 follow along download slides © 2013 Armando Fox & David Patterson, all rights reserved

The Big Picture (Technologies) • URI’s, HTTP, TCP/IP stack • REST & RESTful routes Controller View Model NOTE: Rails doesn't appear anywhere on this slide!! • Databases & migrations • CRUD • HTML & CSS • XML & XPath

c. 2008: “Rails doesn’t scale” Scalability is an architectural concern - not confined to language or framework The stateless tiers of 3-tier arch do scale With cloud computing, just worry about constants Traditional relational databases do not scale Various solutions combining relational and non-relational storage (“NoSQL”) scale much better DataMapper works well with some of them Intelligent use of caching (later in course) can greatly improve the constant factors

Frameworks, Apps, Design Patterns Many design patterns so far, more to come In 1995, it was the wild west: biggest Web sites were minicomputers, not 3-tier/cloud Best practices (patterns) “extracted” from experience and captured in frameworks But API’s transcended it: 1969 protocols + 1960s markup language + 1990 browser + 1992 Web server works in 2011

Architecture is About Alternatives Pattern we’re using Alternatives Client-Server Peer-to-Peer Shared-nothing (cloud computing) Symmetric multiprocessor, shared global address space Model-View-Controller Page controller, Front controller, Template view Active Record Data Mapper RESTful URIs (all state affecting request is explicit) Same URI does different things depending on internal state As you work on other SaaS apps beyond this course, you should find yourself considering different architectural choices and questioning the choices being made

Summary: Architecture & Rails Model-view-controller is a well known architectural pattern for structuring apps Rails codifies SaaS app structure as MVC Views are Haml w/embedded Ruby code, transformed to HTML when sent to browser Models are stored in tables of a relational database, accessed using ActiveRecord Controllers tie views and models together via routes and code in controller methods

END

Relational databases scale better than “NoSQL” databases Other factors being equal, which statement is NOT true regarding SaaS scalability? Shared-nothing clusters scale better than systems built from mainframes ☐ Relational databases scale better than “NoSQL” databases ☐ The programming language used (Ruby, Java, etc.) isn’t a main factor in scalability ☐ True False. True. Scalability can be impeded by any part of the app that becomes a bottleneck ☐

END

© 2013 Armando Fox & David Patterson, all rights reserved Hello Rails: from Zero to CRUD (Engineering Software as a Service §4.1) © 2013 Armando Fox & David Patterson, all rights reserved

Connecting Arch. Concepts to Rails Apps Gemfile Rakefile app /models/, views/, controllers/ /helpers /assets/stylesheets/application.css config /routes.rb /database.yml db /development.sqlite3, test.sqlite3 /migrate/ log /development.log, test.log Gemfile: which libraries does app depend on, so can ensure same versions installed in production. Gem is a Ruby library file. Rakefile: you've already used 'rake routes' in book and lecture examples. Rake is Ruby make.

Rails as an MVC Framework Model, View, Controller Relational Database Persistence: mysql or sqlite3 tables models/*.rb Subclasses of ActiveRecord::Base, an object-relational mapping layer your app Logic: your code & Rack appserver controllers/*.rb Rails routing views/*.html.haml Rails rendering Presentation: WEBrick, Apache, etc. Subclasses of ActionView Subclasses of ApplicationController Client: Firefox

A Trip Through a Rails App Routes (in routes.rb) map incoming URL’s to controller actions and extract any optional parameters Route’s “wildcard” parameters (eg :id), plus any stuff after “?” in URL, are put into params[] hash accessible in controller actions Controller actions set instance variables, visible to views Subdirs and filenames of views/ match controllers & action names Controller action eventually renders a view app/controllers/movies_controller.rb def show id = params[:id] @mv=Movie.find(id) end app/views/movies/show.html.haml %li Rating: = @mv.rating config/routes.rb GET /movies/:id {:action=>'show',:controller=>'movies'}

Rails Philosophy Convention over configuration If naming follows certain conventions, no need for config files MoviesController#show in movies_controller.rb  views/movies/show.html.haml Don’t Repeat Yourself (DRY) mechanisms to extract common functionality Both rely heavily on Ruby features: introspection and metaprogramming blocks (closures) modules (mix-ins)

END

Why must every interaction with a SaaS app eventually cause something to be rendered? Because of convention over configuration ☐ Because HTTP is a request-reply protocol ☐ Because Model-View-Controller implies that every action renders its own View ☐ False. Not in general. True. False. Two views could be called by same action. False. All of the above ☐

END