Showing posts with label Frameworks. Show all posts
Showing posts with label Frameworks. Show all posts

Tuesday, May 20, 2008

SilverStripe

SilverStripe is a free and open source programming framework and content management system (CMS) for creating and maintaining websites. The CMS provides an intuitive web-based administration panel, allowing any person to maintain their website without knowledge of markup or programming languages.

SilverStripe offers a flexible MVC development framework known as Sapphire. Much like Ruby on Rails, but for PHP, it ensures developers are capable of extending and enhancing the functionality of the CMS and the website. More importantly, SilverStripe provides developers with complete control of the generated markup; allowing for higher, semantic standards of XHTML.

SilverStripe is released under the terms of the BSD Licence. An abundance of documentation is available from the SilverStripe help website and wiki. An online demonstration of the CMS is located at the SilverStripe demo website.

History

Prior to SilverStripe 2.x, the CMS was commercially available under a proprietary license. Development efforts for SilverStripe 2.X started in late 2005, as a complete overhaul to take advantage of object orientation and new features in PHP5. On 3 February 2007, SilverStripe 2.0.0 was released publicly as free and open source software.

Motivations and reasoning for moving towards an open source development model were the anticipated results of greater exposure, higher quality code and community contributions.
In March 2007, SilverStripe was selected for the Google Summer of Code programme. The contributions of the students who participated in the programme ultimately resulted in the 2.2 release of SilverStripe.

On 29 November 2007, SilverStripe announced they would be participating in the Google Highly Open Participation (GHOP) contest. This let to a proliferation of themes, translations and widgets that broadened the system.

Features and Add-ons

Notable features include multiple methods of organising navigation through folksonomy, a flexible data object model, multiple templates per page, a separate "Draft site" and "Published site" through staging content, asset management, image resizing, versioning control, search engine friendly URLS with meta-data, automatic sitemap generation, full text search and RSS feeds. SilverStripe supports UTF-8 and the internationalisation of character sets; the CMS is currently available in French, German, Spanish, Chinese, Croatian, Dutch, Polish and Portuguese.

Modules

The highly modular nature of SilverStripe has resulted in the creation of numerous pre-build modules that extend the core functionality of the CMS. A list of available modules is viewable below:

  • Blog
  • E-commerce
  • Embargo/expiry
  • External Authentication (LDAP, AD, etc)
  • Flickr Gallery
  • Forum
  • Gallery
  • Maps
  • Technorati
  • Youtube Gallery

Widgets

Widgets are small pieces of useful functionality that can be instantly dragged and dropped into a website. A list of available modules is viewable below:

  • Built-in widgets for the blog module
  • Countdown
  • Del.icio.us
  • Digg
  • Featured Video
  • Feedburner
  • Feedburner Email Subscription
  • Google Adsense
  • Google Custom Search
  • IMStatus
  • LanguageChooser
  • last.fm
  • Links
  • NASA image of the day
  • New Users
  • Ohloh contribution
  • PayPal donation
  • Popular Blog Posts
  • Recent Page Comments
  • Time
  • TwitterStatus
  • WoW Character

Themes

The SilverStripe themes directory provides a number of community-contributed, freely available themes; providing developers and website owners with the capability to instantly modify the aesthetics of their SilverStripe website.

Software Requirements

SilverStripe is a web application, requiring a compatible HTTP server and SQL database. As of version 2.2.0 (28 November 2007), the requirements for SilverStripe are as follows:

List of web application frameworks

This is a list of notable web application frameworks, used for creating web applications.

Client-side

ActionScript

JavaScript

Further information: JavaScript library

Server-side

PHP

JavaScript (server-side)

Ruby

Perl

ColdFusion

ASP

ASP.NET

Java

Python

Other languages/Multiple languages

Ajax framework

An Ajax framework is a framework that helps to develop web applications that use Ajax, a collection of technologies used to build dynamic web pages on the client side. Data is read from the server or sent to the server by JavaScript requests. However, some processing at the server side may be required to handle requests, such as finding and storing the data. This is accomplished more easily with the use of a framework dedicated to process Ajax requests. The goal of the framework is to provide the Ajax engine described below and associated server and client-side functions.

Benefit of a framework

In the article that coined the "Ajax" term, J.J. Garrett describes the technology as "an intermediary...between the user and the server." This Ajax engine is intended to suppress the delays perceived by the user when a page attempts to access the server. A framework eases the work of the Ajax programmer at two levels: on the client side, it offers JavaScript functions to send requests to the server. On the server side, it processes the requests, searches for the data, and transmits them to the browser. Some frameworks are very elaborate and provide a complete library to build web applications.

Types of frameworks

Ajax frameworks can be loosely grouped into categories according to the features they offer and the skills required of the user:

Direct Ajax frameworks

These frameworks require HTML, CSS and Ajax expertise: a developer is expected to author pages directly in HTML, and framework APIs deal directly with HTML elements.

Cross-browser APIs are provided for a variety of purposes, commonly including communications, DOM manipulation, event handling, and sizing/moving/animating HTML elements.

These frameworks are generally smaller. They are commonly used for a web site such as a shopping experience, but not for a web application such as web-based email, at least not without further frameworks layered on top.

Ajax component frameworks

These frameworks offer pre-built components, such as tabbed panes, which automatically create and manage their own HTML. Components are generally created via JavaScript or XML tags, or by adding special attributes to normal HTML elements. These frameworks are generally larger, and intended for web applications rather than web sites.

Some component frameworks require the developer to have extensive HTML/CSS/Ajax experience and to do cross-browser testing. For example, grids, tabs, and buttons may be provided, but user input forms are expected to be authored directly in HTML/CSS and manipulated via Ajax techniques. Other frameworks provide a complete component suite such that only general XML and/or JavaScript abilities are required.

Ajax component frameworks can enable more rapid development than direct Ajax frameworks, but with less control, hence it is key that an Ajax component framework provides the following:

  • customization APIs, e.g., an event that fires when the user stops editing within a grid
  • skinning facilities, where appearance can be changed without affecting behavior or layout
  • programmatic control, e.g., dynamically adding tabs or dynamically creating components based on user data
  • extensibility—creation of new components based on other components, so that the benefits of a component-based framework are not lost

Server-driven Ajax frameworks

Several frameworks offer a server-side component-based development model with some degree of Ajax support.

Components are created and manipulated on the server using a server-side programming language. Pages are then rendered by a combination of server-side and client-side HTML generation and manipulation. User actions are communicated to the server via Ajax techniques, server-side code manipulates a server-side component model, and changes to the server component model are reflected on the client automatically.

These frameworks offer familiarity for server-side developers at the expense of some degree of power and performance. Ajax frameworks that handle presentation completely within the browser offer greater responsiveness because they handle many more user interactions without server involvement. In a server-driven model, some UI interactions can become chatty, for example an input field that is dynamically enabled or disabled based on server-side code may cause many network requests. Furthermore, server-dependent Ajax frameworks will never be able to offer offline support. Still, this approach is popular, especially in situations where the benefits of a full Ajax architecture can't be captured anyway.

Extending such a framework may require the developer to understand which parts of the presentation are handled on the client vs on the server, and to write a mixture of Ajax and server-side code.

Frameworks and languages/platforms

JavaScript

JavaScript utilities run browser-side and are very commonly used in Ajax development. There are many JavaScript utilities available. Prototype is a JavaScript extension that provides utilities to complement the short comings of JavaScript. Script.aculo.us is used with the Prototype Framework, mainly utilities for animations. Yahoo! UI Library is a set of utilities and controls, for building richly interactive web applications using techniques such as DOM scripting, DHTML and Ajax. In addition to JavaScript utilities there are more complete Ajax Frameworks that provide utilities, pre-build widgets, debugging tools and visual Ajax development tools and client-server sync capabilities. Dojo Toolkit is a Javascript library and widgets architected to provide semantic extensions to HTML.

PHP

A PHP framework is able to deal with database, search data, and build pages or parts of page and publish the page or return data to the XMLHttpRequest object. PHP 5 specifically, thanks to its SimpleXML class, is able to create XML files that may be returned to the object. However, it is better to use a predefined library that performs the various tasks, for example Sajax, a PHP framework with a lot of functions, easy to integrate functions yourself or Xajax that uses only the XML format, on the server side.

Java

Such frameworks use Java for server-side AJAX operations. The Google Web Toolkit, a widget library with Java to JavaScript compiler is widely used by webmasters.

.NET

The Ajax.NET Professional and ASP.NET AJAX (previously Microsoft Atlas) frameworks are available for the Windows .NET platform.

C++

C++ Toolkits are interfaces to Ajax technology. For example Wt (witty) is a WebToolkit allowing programmers to write code in C++ (without real knowledge of Ajax), generating content rich Ajax GUI. OpenSource Licence.

List of Ajax frameworks

From Wikipedia, the free encyclopedia

This is a list of notable Ajax frameworks, used for creating web applications with a dynamic link between the client (and sometimes the server).

JavaScript

JavaScript Frameworks are browser-side frameworks very commonly used in Ajax development. There are hundreds of JavaScript frameworks available — according to the last surveys, the most used JavaScript frameworks are:

Framework
Backbase, an Enterprise Ajax Framework for creating Rich Internet Applictions
Dojo Toolkit, an Open Source DHTML toolkit written in JavaScript
Ext (javascript library), a library that extends Prototype, Jquery and YUI
jQuery, a JavaScript framework that provides an Ajax framework and other utilities
Mootools, a compact and modular JavaScript framework best known for its visual effects and transitions
Prototype, a JavaScript framework that provides Ajax and other utilities
Script.aculo.us, Used with the Prototype Framework, mainly for animations and interface development
Yahoo! UI Library, a set of utilities and controls, for building richly interactive web applications using techniques such as DOM scripting, DHTML and Ajax

Other frameworks not among the most used includes:

  • Clean AJAX, framework also able to deal with web services

C++

C++ Toolkits are interfaces to Ajax technology

  • Wt (witty) is a WebToolkit, allowing programmers to write code in C++ (without real knowledge of Ajax), generating content rich Ajax GUI. OpenSource Licence.

Java

These frameworks use Java for server-side AJAX operations:

  • Backbase, Enterprise Ajax for JSF (Java Server Faces)
  • Echo, a Java framework for Ajax servlets
  • Google Web Toolkit, a widget library with Java to JavaScript compiler
  • DWR, Direct Web Remoting, DWR allows Javascript in a browser to interact with Java on a server and helps you manipulate web pages with the results.
  • jMaki, an AJAX framework that can be plugged into netbeans or eclipse IDE

.NET

The following frameworks are available for the Windows .NET platform:

ColdFusion

The following frameworks are available for ColdFusion:

PHP

A PHP framework is able to deal with database, search data, and build pages or parts of page and publish the page or return data to the XMLHttpRequest object. PHP 5 specifically, thanks to its SimpleXML class, is able to create XML files that may be returned to the object. However, it is better to use a predefined library that performs the various tasks.

  • Sajax Is a PHP framework with a lot of functions, easy to integrate functions yourself.
  • Tigermouse is a modern Ajax driven MVC framework for web applications development.
  • Xajax uses only the XML format, on the server side.

Friday, May 9, 2008

Prototype JavaScript framework

Prototype code sample

Prototype is a JavaScript Framework that aims to ease development of dynamic web applications.

Featuring a unique, easy-to-use toolkit for class-driven development and the nicest Ajax library around, Prototype is quickly becoming the codebase of choice for web application developers everywhere.

How Prototype extends the DOM

The biggest part of the Prototype framework are its DOM extensions. Prototype adds many convenience methods to elements returned by the $() function: for instance, you can write $('comments').addClassName('active').show() to get the element with the ID 'comments', add a class name to it and show it (if it was previously hidden). The 'comments' element didn't have those methods in native JavaScript; how is this possible? This document reveals some clever hacks found in Prototype.

The Element.extend() method

Most of the DOM methods are encapsulated by the Element.Methods object and then copied over to the Element object (for convenience). They all receive the element to operate with as the first parameter:


Element.hide('comments');
var div_height = Element.getHeight(my_div);
Element.addClassName('contactform', 'pending');

These examples are concise and readable, but we can do better. If you have an element to work with, you can pass it through Element.extend() and it will copy all those methods directly to the element. Example, to create an element and manipulate it:


var my_div = document.createElement('div');


Element.extend(my_div);
my_div.addClassName('pending').hide();


// insert it in the document
document.body.appendChild(my_div);

Our method calls just got shorter and more intuitive! As mentioned before, Element.extend() copies all the methods from Element.Methods to our element which automatically becomes the first argument for all those functions. The extend() method is smart enough not to try to operate twice on the same element. What's even better, **the dollar function $() extends every element passed through it** with this mechanism.

In addition, Element.extend() also applies Form.Methods to FORM elements and Form.Element.Methods to INPUT, TEXTAREA and SELECT elements:


var contact_data = $('contactform').serialize();
var search_terms = $('search_input').getValue();

Note that not only the dollar function automatically extends elements! Element.extend() is also called in document.getElementsByClassName, Form.getElements, on elements returned from the $$() function (elements matching a CSS selector) and other places - in the end, chances are you will rarely need to explicitly call Element.extend() at all.

Adding your own methods with Element.addMethods()

If you have some DOM methods of your own that you'd like to add to those of Prototype, no problem! Prototype provides a mechanism for this, too. Suppose you have a bunch of functions encapsulated in an object, just pass the object over to Element.addMethods():


var MyUtils = {
    truncate: function(element, length){
        element = $(element);
        return element.update(element.innerHTML.truncate(length));
    },
    updateAndMark: function(element, html){
        return $(element).update(html).addClassName('updated');
    }
}


Element.addMethods(MyUtils);


// now you can:
$('explanation').truncate(100);

The only thing to watch out here is to make sure the first argument of these methods is the element itself. In your methods, you can also return the element in the end to allow for chainability (or, as practiced in the example, any method which itself returns the element).

Native extensions

There is a secret behind all this.

In browsers that support adding methods to prototype of native objects such as HTMLElement all DOM extensions on the element are available by default without ever having to call Element.extend(), dollar function or anything! This will then work in those browsers:


var my_div = document.createElement('div');
my_div.addClassName('pending').hide();
document.body.appendChild(my_div);

Because the prototype of the native browser object is extended, all DOM elements have Prototype extension methods built-in. This, however, isn't true for IE which doesn't let anyone touch HTMLElement.prototype. To make the previous example work in IE you would have to extend the element with Element.extend(). Don't worry, the method is smart enough not to extend an element more than once.

Because of browsers that don't support this you must take care to use DOM extensions only on elements that have been extended. For instance, the example above works in Firefox and Opera, but add Element.extend(my_div) after creating the element to make the script really solid. You can use the dollar function as a shortcut like in the following example:


// this will error out in IE:
$('someElement').parentNode.hide()
// to make it cross-browser:
$($('someElement').parentNode).hide()

Don't forget about this! Always test in all the browsers you plan to support.

Defining classes and inheritance

In the early versions of Prototype, the framework came with basic support for class creation: the Class.create() method. Until now the only feature of classes defined this way was that the constructor called a method called initialize automatically. Prototype 1.6.0 now comes with inheritance support through the Class module, which has taken several steps further since the last version; you can make richer classes in your code with more ease than before.

The cornerstone of class creation in Prototype is still the Class.create() method. With the new version of the framework, your class-based code will continue to work as before; only now you don't have to work with object prototypes directly or use Object.extend() to copy properties around.

Example

Let's compare the old way and a new way of defining classes and inheritance in Prototype:

/** obsolete syntax **/ 


var Person = Class.create();
Person.prototype = {
  initialize: function(name) {
    this.name = name;
  },
  say: function(message) {
    return this.name + ': ' + message;
  }
};


var guy = new Person('Miro');
guy.say('hi');
// -> "Miro: hi"

var Pirate = Class.create();
// inherit from Person class:
Pirate.prototype = Object.extend(new Person(), {
  // redefine the speak method
say: function(message) {
    return this.name + ': ' + message + ', yarr!';
  }
});


var john = new Pirate('Long John');
john.say('ahoy matey');
// -> "Long John: ahoy matey, yarr!"

Observe the direct interaction with class prototypes and the clumsy inheritance technique using Object.extend. Also, with Pirate redefining the say() method of Person, there is no way of calling the overridden method like you can do in programming languages that support class-based inheritance.

This has changed for the better. Compare the above with:

/** new, preferred syntax **/ 


// properties are directly passed to `create` method
var Person = Class.create({
  initialize: function(name) {
    this.name = name;
  },
  say: function(message) {
    return this.name + ': ' + message;
  }
});


// when subclassing, specify the class you want to inherit from
var Pirate = Class.create(Person, {
  // redefine the speak method
say: function($super, message) {
    return $super(message) + ', yarr!';
  }
});


var john = new Pirate('Long John');
john.say('ahoy matey');
// -> "Long John: ahoy matey, yarr!"

You can see how both class and subclass definitions are shorter because you don't need to hack their prototypes directly anymore. We have also demonstrated another new feature: the "supercall", or calling the overridden method (done with special keyword super in the Ruby language) in Pirate#say.

How to mix-in modules

So far you have seen the general way of calling Class.create.

var Pirate = Class.create(Person, { /* instance methods */ }); 

But in fact, Class.create takes in an arbitrary number of arguments. The first—if it is another class—defines that the new class should inherit from it. All other arguments are added as instance methods; internally they are subsequent calls to addMethods (see below). This can conveniently be used for mixing in modules:

// define a module 
var Vulnerable = {
  wound: function(hp) {
    this.health -= hp;
    if (this.health < 0) this.kill();
  },
  kill: function() {
    this.dead = true;
  }
};


// the first argument isn't a class object, so there is no inheritance ...
// simply mix in all the arguments as methods:
var Person = Class.create(Vulnerable, {
  initialize: function() {
    this.health = 100;
    this.dead = false;
  }
});


var bruce = new Person;
bruce.wound(55);
bruce.health; //-> 45

The $super argument in method definitions

When you override a method in a subclass, but still want to be able to call the original method, you will need a reference to it. You can obtain that reference by defining those methods with an extra argument in the front: $super. Prototype will detect this and make the overridden method available to you through that argument. But, from outside world the Pirate#say method still expects a single argument; this implementation detail doesn't affect how your code interacts with the objects.

Types of inheritance in programming languages

Generally we distinguish between class-based and prototypal inheritance, the latter being specific to JavaScript. While upcoming JavaScript 2.0 will support true class definitions, current versions of the JavaScript language implemented in modern browsers are restricted to prototypal inheritance.

Prototypal inheritance, of course, is a very useful feature of the language, but is often too verbose when you are actually creating your objects. This is why we are emulating class-based inheritance (like in the Ruby language) through prototypal inheritance internally. This has certain implications. For instance, in PHP you can define the inital values for instance variables:

class Logger {    
public $log = array();
function write($message) {
$this->log[] = $message;
}
}
$logger = new Logger;
$logger->write('foo');
$logger->write('bar');
$logger->log; // -> ['foo', 'bar']

We can try to do the same in Prototype:

var Logger = Class.create({ 
  initialize: function() { },
  log: [],
  write: function(message) {
    this.log.push(message);
  }
});


var logger = new Logger;
logger.log; // -> []
logger.write('foo');
logger.write('bar');
logger.log; // -> ['foo', 'bar']

It works. But what if we make another instance of Logger?

var logger2 = new Logger; 
logger2.log; // -> ['foo', 'bar']

// ... hey, the log should have been empty!

You can see that, although some of you expected an empty array in the new instance, we have the same array as the previous logger. In fact, all logger objects will share the same array object because it is copied by reference, not by value. The correct way is to initialize your instances to default values:

var Logger = Class.create({ 
  initialize: function() {
    // this is the right way to do it:
this.log = [];
  },
  write: function(message) {
    this.log.push(message);
  }
});

Defining class methods

There is no special support for class methods in Prototype 1.6.0. Simply define them on your existing classes:

Pirate.allHandsOnDeck = function(n) { 
  var voices = [];
  n.times(function(i) {
    voices.push(new Pirate('Sea dog').say(i + 1));
  });
  return voices;
}


Pirate.allHandsOnDeck(3);
// -> ["Sea dog: 1, yarr!", "Sea dog: 2, yarr!", "Sea dog: 3, yarr!"]

If you need to define several at once, simply use Object.extend as before:

Object.extend(Pirate, { 
  song: function(pirates) { ... },
  sail: function(crew) { ... },
  booze: ['grog', 'rum']
});

When you inherit from Pirate, the class methods are not inherited. This feature may be added in future versions of Prototype. Until then, copy the methods manually, but not like this:

var Captain = Class.create(Pirate, {}); 
// this is wrong!
Object.extend(Captain, Pirate);

Class constructors are Function objects and it will mess them up if you just copy everything from one to another. In the best case you will still end up overriding subclasses and superclass properties on Captain, which is not good.

Special class properties

Prototype 1.6.0 defines two special class properties: subclasses and superclass. Their names are self-descriptive: they hold references to subclasses or superclass of the current class, respectively.

Person.superclass 
// -> null
Person.subclasses.length
// -> 1
Person.subclasses.first() == Pirate
// -> true
Pirate.superclass == Person
// -> true
Captain.superclass == Pirate
// -> true
Captain.superclass == Person
// -> false

These properties are here for easy class introspection.

Adding methods on-the-fly with Class#addMethods()

Class#addMethods was named Class.extend in Prototype 1.6 RC0.
Please update your code accordingly.

Imagine you have an already defined class you want to add extra methods to. Naturally, you want those methods to be instantly available on subclasses and every existing instance in the memory! This is accomplished by injecting a property in the prototype chain, and the safest way to do it with Prototype is to use Class#addMethods:

var john = new Pirate('Long John'); 
john.sleep();
// -> ERROR: sleep is not a method

// every person should be able to sleep, not just pirates!
Person.addMethods({
  sleep: function() {
    return this.say('ZzZ');
  }
});


john.sleep();
// -> "Long John: ZzZ, yarr!"

The sleep method was instantly available not only on new Person instances, but on its subclasses and existing instances currently in memory.

Friday, April 4, 2008

The Simplicity PHP Framework!

The Simplicity PHP Framework!

The Simplicity PHP Application Framework is an advanced, scalable and extensible PHP application framework to aid developers in creating high traffic, high availability Web 2.0 online applications. Integrating a solid MVC framework with some of the best Open Source projects around Simplicity aims to assist developers with any amount of experience in taking their applications to a new level.

Mission Statement

Create and evolve a fast and lightweight, yet robust, complete and secure PHP framework, aiding and supporting the PHP developer who wants to use and deploy all the new and exciting Web 2.0 features fast and easy, without the need to become an expert in all the different aspects.

Features

  • Fast and lightweight OO-MVC framework.
  • Tight integration of one of the finest JavaScript frameworks available, Ext 2.0.
  • Full AJAX enabled control panel to manage all aspects of you application this includes database modeling and the creation of stub controllers, and even the addition of predefined actions to speed up development.
  • Database modeling and the creation of stub controllers with the Admin console.
  • Addition of predefined actions to speed up development.
  • Flexible Data Models architecture to allow accessing and even creating relations with almost any data source, Including RDBMS, RSS, LDAP, XML or even just plain text.
  • 100% Buzzword compliant!

Quick intro to Simplicity

Here are some screen shots to give you a taster for the admin console...

This is the 'home tab' of the admin console. Here you can see a quick into to simplicity and a dynamic, real time usage monitor, this gives you the current page views / sec across the site.

This is the 'Registry' of the simplicity application. This is an XML backed cascading hierarchical configuration used you use to hold all configuration for your site. But this is not limited to single, key/value types on information, you can for example store the navigational structure of your application within the registry, so you could have a container called home, and within there a container called children, and in there keys for the children etc. etc. This can be accessed in code as follows:

<? /*
This code refers to the following tree:

navigation
home
info -> 'The info page'
contact -> 'The contact page'
*/
// Here we use the shortcut class to Simplicity_Registry: SRG
$nav = SRG::get('navigation'); // returns the entire navigation tree as an multidimensional array.
$nav = SRG::get('navigation.home'); // returns just the home container as an associative array.
$nav = SRG::get('navigation.home.info'); // here we return the value of the info key, as a string.
?>


This shows the context menus of the Registry tree, showing how you can add keys and containers to the registry.

This is the popup for adding a new root level item to the registry.

This shows the Application Structure section of the application, this is used to display all the current controllers and their methods, currently it is read only, but here you will be able to assign routes (custom URIs) to methods, and even create controllers from scratch directly within the interface.

This shows the data modeling tab of the console. This allows you to create connections to a variety of different data sources, including all RDBMS' supported by php PDOs, CSV and TSV files and raw PHP arrays, with support on the horizon for RSS feeds and more. Once created you can create Models associated with the connections, you do this by creating the model using the context menu, then adding column definitions, each column is a container and contains a variety of properties. Internally all of this is stored in the Registry, showing just how flexible it can be. When a model is defined it can be accessed in the code is a variety of ways:

<?
// Again here we are using the shortcut class for Simplicity_Data : SDA

//Request a specific model directly by id
$user = SDA::getModel('simplicity.users',1);

print $user->name; //outputs the value of the 'name' field.

//Request a group of models using MQL - this will request all the users.
$users = SDA::query('select simplicity.users');

foreach ($users as $user) {
print $user->name.'</br>'; // outputs a list of all users
}

//Filter the results with where and limit
// users with names starting with J.
$users = SDA::query('select simplicity.users where name like "j%"');

// the first 10 users
$users = SDA::query('select simplicity.users limit 10');

// the next ten users, (offset by 10)
$users = SDA::query('select simplicity.users limit 10,10');

//Ordering
// show all users sort by name
$users = SDA::query('select simplicity.users order by name');

// show all users sort by kudos in reverse order.
$users = SDA::query('select simplicity.users order by kudos desc');

?>

Thursday, April 3, 2008

Model View Controller

Model View Controller

Model View Controller MVC is a time tested method of separating the user interface of an application from its Domain Logic.

The primary goal of MVC is to isolate UI changes and prevent them from requiring changes to the Domain Logic of the application.

The primary reason for this division is that the user interface and Domain Logic have different drivers for change and different rates of change. By making this separation, you can change the UI without touching the Domain Logic and vice versa.

MVC is sometimes confused with other patterns that have the same goal of separating user interface from Domain Logic, such as Presentation Abstraction Control.

MVC divides an application into three concerns:

  • Model - Encapsulates core application data and functionality Domain Logic.
  • View - obtains data from the model and presents it to the user.
  • Controller - receives and translates input to requests on the model or the view.


The separation into three concerns is inspired by a information processing model where the controller represents system input, the model represents processing and the view represents the output of the system.


Model

The model encapsulates the functional core of an application, its Domain Logic. The goal of MVC is to make the model independent of the view and controller which together form the user interface of the application. An object may act as the model for more than one MVC triad at a time.

Since the model must be independent, it cannot refer to either the view or controller portions of the application. The model may not hold direct instance variables that refer to the view or the controller. It passively supplies its services and data to the other layers of the application.

See Domain Model and Transaction Script to organize Domain Logic.


Passive Model

With a passive model, the objects used in the model are completely unaware of being used in the MVC triad. The controller notifies the view when it executes an operation on the model that will require the view to be updated.

The passive model is commonly used in web MVC. The strict request/response cycle of HTTP does not require the immediacy of an active model. The view is always completely re-rendered on every cycle, regardless of changes. This may be especially true in PHP where no state is retained between requests.

Active Model

In the active model, model classes define a change notification mechanism, typically using the Observer pattern. This allows unrelated view and controller components to be notified when the model has changed. Because these components register themselves with the model and the model has no knowledge of any specific view or controller, this does not break the independence of the model.

This notification mechanism is what provides the immediate updating that is the hallmark of a MVC GUI application.

Model Adapter

It is possible to use an Adapter to add change propagation or other active model features to passive model objects, turning a passive model into an active model.


Presentation Model

The purpose of MVC is to separate UI from domain logic. In doing so, an MVC implementation typically develops a set of reusable classes for each of the concerns in the triad. Sometimes, data or behavior that firmly belongs on the user interface side of the division can conveniently be represented using the infrastructure of the model side of the division. Thus objects that would appear at first glance to be in the model are really part of the interface concern, that is the view and controller.

Some examples include scrollbar positions and column sorting.

This is sometimes called an Application Model and the pattern known as MMVC after the idea that there are two separate models.


View

The view obtains data from the model and presents it to the user. The view represents the output of the application.

The view generally have free access to the model, but should not change the state of the model. Views are read only representations of the state of the model. The view reads data from the model using query methods provided by the model.

With an Active model, the view can register itself to receive notifications when the model changes, and the view can then present a more up to date version of the model.

Sometimes generic reusable view components can be arbitrarily connected to the model in a process known as binding.

See Template View and Transform View for strategies of implementing views.


Controller

The controller receives and translates input to requests on the model or view.

The controllers are typically responsible for calling methods on the model that change the state of the model. In an active model, this state change is then reflected in the view via the change propagation mechanism. In the passive model, the controller is responsible for telling the view when to update.

In MVC, The controller is NOT a Mediator between the view and the model. The controller does not sit in between the model and the view. Both the controller and the view have equal opportunity to access the model. The controller does not copy data values from the model to the view, although it may place values in the model and tell the view that the model has changed. see Presentation Abstraction Control where the control layer acts as a mediator between Presentation and Abstraction.

The word controller is overloaded with different meanings in various patterns. see what is a Controller Anyway There are several of these controller patterns: Front Controller A single point of dispatch for incoming http requests. Page Controller Controls the flow of logic of a single web page. Application Controller Controls the flow of logic of a single application.

Because the popular MVC framework Java Struts from a PHP Perspective implements a combined Front Controller and Application Controller, some people assume that this is what is meant by the MVC pattern in the context of a web application. For the same reason, many descriptions of the Front Controller pattern on the web do not draw the distinction between a Front Controller and a Application Controller.


Relationships between components


View Controller Relationship

In traditional smalltalk MVC, views and controllers are tightly coupled. Each view instance is associated with a single unique controller instance and vise versa. The controller is considered a Strategy that the view uses for input. The view is also responsible for creating new views and controllers.

It is logical that views and controllers are strongly related, the input and output of an application is strongly related. In most GUI MVC frameworks, the view and controller are simply merged into one object. This is called Document View. The view and controller are combined as the view. The model becomes known as a document.

A passive model shifts more responsibility into the controller, as it must notify the views when they should update.

The modern web usage of MVC shifts even more of the traditional responsibilities of the view to the controller. The controller becomes responsible for creating and selecting views and the view tends to lose responsibility for its controller.

Sometimes responsibility for creating and selecting views is delegated to a specific object, this is known as the Application Controller pattern for web MVC and View Handler for GUI MVC.

The rigid request/response cycle of HTTP may make the Document View variant less popular in web applications than in GUI applications although the controller is still strongly related to the view. The HTTP request is handled by the controller, the processing to the model, and the response is handled by the view.


Model View Relationship

The view depends on the model. Changes to the model interface require parallel changes in the view.

It is very difficult to achieve a strict separation between the model and view. For example, consider the requirement “Show negative balances in red.” At first glance, this appears to be strictly an output requirement and a test might be placed into the view in roughly this form:

if balance <>

This would violate the separation of concerns in MVC. Upon further analysis it turns out that the real requirement is “show overdrawn balances in red” and the definition of overdrawn =balance < 0= should be placed in the model as that is domain specific. It is very easy for domain logic to migrate out of the model and into the view. Template View contains further discussion of this issue.


Model Controller Relationship

The Controller depends on the model. Changes to the model interface may require parallel changes to the controller.


Scale and Granularity

The MVC pattern is applicable at many different scales in an application. At the lowest level, an object oriented implementation involves three objects two with Document View. Although three objects are involved, only a portion of each object may be involved in any given MVC triad at the smallest scale. For example, a checkbox view/controller component operates on a data value from a model object. MVC is the easiest to understand and implement at the lowest level of granularity.

These small triads can be combined and composed into larger and larger triads. checkboxes and text fields into panels, panels into windows, windows into applications, etc. At each level, the separations mandated by MVC are maintained. At the higher levels, each concern might be considered a layer or package containing specific classes.

If the MVC separations are maintained at the lowest scale, it should follow that they are maintained on every higher scale.

If the three MVC concerns were simply separated into three classes for a non-trivial example, each of those classes would end up as a Big Ball Of Mud and would hardly be re-usable. Others patterns should be applied to structure the individual concerns of MVC.


Structuring views

Composite View.

The Composite pattern can be applied to the view giving it a hierarchical structure. This pattern is known as Composite View. Views are easy to decompose by partitioning the visual output of the application into nested rectangles that form the composite hierarchy.

This partitioning of the view layer creates smaller more focused view components which have more opportunity for re-use.


Structuring controllers

Because the controllers are so closely related to the view, they can also be partitioned with a parallel hierarchy to the Composite View. This is common with GUI MVC. One advantage of the Document View variant is that it is unnecessary to maintain two parallel hierarchies in this case.

The Command Pattern pattern is often used to structure the controller concern of the MVC triad. A specific set of model/view interactions is encapsulated into a command object, often called an action in the web MVC. This is commonly used in GUI MVC as well as Web MVC.

An action should not be confused with a Transaction Script. Just as it is easy for Domain Logic to bleed into the view, it is also easy for Domain Logic to bleed into the actions of the controller layer. Actions should translate input into requests on the model, create or select views, and generally provide user interface oriented services.

Actions promote reuse. They can be parameterized.

In any structuring of the controller concern, Input must be distributed to the correct controller sub components. In a GUI application, the Chain of Responsibility pattern is used along with the visual hierarchy defined by the Composite View to route input to the correct controller. _how to route input in web MVC?


Structuring models

The Domain Model and Transaction Script patterns are used to organize Domain Logic.

The Command Pattern pattern can be used in organizing Domain Logic, often as a way of implementing a Transaction Script. Using the Command pattern can promote re-use of domain logic, especially when parameterized.


Platform Independence

Typically each concern of the MVC triad has ties to a specific platform. It is possible to isolate these platform dependencies from the platform independent portions of the application by splitting each concern using the Bridge pattern.

The Context Object Pattern provides platform independence from the web server for the user interface view and controller of a web application.

The Data Access Object provides platform independence from the database server for the model of an application.


Benefits of MVC


Substitutable user interface

Different views and controllers can be substituted to provide alternate user interfaces for the same model. For example, the same model data can be displayed as a bar graph, or a pie chart, or a spreadsheet.

Some examples: Read only UI Expert and novice specific UI Different human languages Alternate input mechanisms User specific themes Alternate output formats XML, HTML, etc Alternate form mechanisms HTML forms, XForms, PDF forms


User interface components

Because MVC demands that the user interface of an application be structured into a hierarchy of objects and defines a standard relationship between these objects, generic versions of these objects are possible. They are usually called user interface components and no modern GUI environment is without a full complement of them usually combining view and controller into a single object. WACT is an attempt to provide a similarly rich set of components for web development that maintain the separation between view and controller. components promote reuse and reduce the need for special subclasses. These are known as “pluggable views” in the smalltalk MVC literature.


Multiple simultaneous views of the same model

Multiple different views can be active at the same time. Each view simultaneously and independently presents the same information from the model. This applies more to GUI MVC than web MVC.


Syncronized views

The change propagation mechanism insures that all views simultaneously reflect the current state of the model.


Easier user interface changes

Changes affecting just the user interface of the application logic become easier to make.


Easier testing

With MVC it can be easier to test the core of the application, as encapsulated by the model.


Drawbacks of MVC


Increased complexity

If reading this page doesn’t convince of you the complexity of this pattern, consider all of the auxiliary patterns that co-occur with MVC.


Close coupling of views and controllers to model

Changes to the model interface require parallel changes in the view and may require additional changes to the controller. certain code changes become more difficult.


Potential for excessive updates

The change propagation mechanism can be inefficient when frequent model changes require many change notifications. This is generally not as much of a problem if a passive model is used.


Close coupling between view and controller

strict separation is difficult if not impossible.


What goes where?

A common question about web MVC is “where does this go?” This question arises from the desire to concretely divide every portion of an application into one portion of the triad. In practice, however, a strict separation of concerns into three parts is difficult to achieve, perhaps impossible. The difficulty of separating view and controller is discussed in the Document View variant. Perhaps the effort to achieve strict separation exhibits diminishing returns and is simply not worth pursuing to the fullest extent.

_talk about how user interface models and domain logic bleed into the view and controller add to the confusion._

_Mediator based definitions of MVC also add to the confusion._

That said, the best guide to partitioning the application is to follow the input, processing, output form of the pattern.


When NOT to use MVC

The need to separate domain logic from presentation is almost an unquestioned axiom of object oriented design. Yet, many successful projects have not done this at all. Standard usage of PHP freely mixed UI and domain logic. Microsoft’s .NET architecture encourages domain logic to be mixed with user interface. Many successful software packages have been written without using the MVC pattern. see Separate Domain From Presentation for an alternate viewpoint.

Implementing MVC is complex and difficult. Following the You Aren't Going to Need It principle, one might hold off implementing MVC in an application until a need for one or more of the benefits of MVC manifests itself. Carefully weigh the benefits and drawbacks of using MVC before implementing this pattern in your application.