Tuesday, May 27, 2008

AJAX-enabled Smarty plugins

Today I’ve created simple AJAX-enabled plugins for Smarty. I don’t try to develop powerful reach-applications framework. I can give you only idea how to integrate AJAX-technology into Smarty. But if you have any offers how to improve anything I’ve described or if you just want to leave feedback please post you comments on my site.

In my practice I need several things from AJAX: to update some nodes in DOM, to send forms without post-back, to retrieve some values or to perform server-side calculation (maybe using database or other server-side resources). It’s necessary to write tons of JavaScript to implement my requirements in spite of using cool JavaScript library Prototype.
I decided to integrate Smarty with AJAX. There are three Smarty plugins has been created: ajax_update, ajax_call, ajax_form. Below all this plugins will be described.

ajax_update

This Smarty function can be used for update some parts of web-page.
Sample usage:

<a  href="#" onclick="{ajax_update update_id='intro_content' function='update_intro' params='page=about'}">About</a> 

Possible parameters:

  • url - URL for AJAX-query (when no URL was specified current one will be used)
  • method - query method (by default get, can be get or post)
  • update_id - ID of HTML element for update
  • function - function which will be called
  • params - URL-encoded parameters

ajax_call

This Smarty function can be used for call PHP function on server side and retrieve its output.

Sample usage:

<a  href="#" onclick="{ajax_call function='calculate'  params_func='calc_params' callback='calc_cb'}">Calculate</a>

Possible parameters:

  • url - URL for AJAX-query (when no URL was specified current one will be used)
  • method - query method (by default get, can be get or post)
  • function - function which will be called
  • params - URL-encoded parameters
  • callback - JavaScript function which will be called when query will be completed
  • params_func - JavaScript function used when you need custom parameters calculated on client side

ajax_form

This Smarty block can be used for submit Web-forms without post-back.

Sample usage:

 {ajax_form method="post" id="form_register"}
Any form-element can be placed here
{/ajax_form}

Possible parameters:

  • url - URL for AJAX-query (when no URL was specified current one will be used)
  • method - query method (by default get, can be get or post)
  • params - URL-encoded parameters
  • id - form ID
  • callback - JavaScript function which will be called when query will be completed

Simplest way is to process form on the server and parse result on client, where return data can be in following format:

true;User was registered successfully;http://example.com/login/ false;Please enter your name;Entered passwords doesn't match

Result string can be splitted on client and results can be shown in some part of page.

Process function may looks like following (it’s part of smarty_ajax):

 var SmartyAjax = {
  onSubmit: function(originalRequest) {
    var results = originalRequest.responseText.split(";");

    if (results[0] == "true") {
      SmartyAjax.Messages.set(results[1],
        SmartyAjax.Messages.MT_WARNING)
    } else {
      SmartyAjax.Messages.clear();
      SmartyAjax.Messages.setType(SmartyAjax.Messages.MT_ERROR);
      for (var i = 1; i < results.length; i++) {
        SmartyAjax.Messages.add(results[i]);
      }
    }
  }
}

This function uses several functions from SmartyAjax.Messages object which depends on following HTML elements:

 <div id="messages">
  <p id="messages-title"></p>
  <ul id="messages-list"></ul>
</div>

To manage messages I’ve created Smarty template parts/warnings.tpl. You can use it in your PHP file in simple way:

 // is messages  contains warning (or error)  $t->assign('messages_warning', true);  // array of messages  $t->assign('messages', array('Please provide your account information')); 

Another thing we need to examine is message which informs user about processing AJAX request. There is SmartyAjax.Process object in the sample which has two methods: hide() and show() which can be used to hide and display message. They are depends on HTML-element with id=”ajax-process”. It’s necessary to add “position: absolute” style because of this messages will be shown in top-right corner of screen independing on scroll position.

 ajax_form is simple to use:
 {ajax_form method="post" id="form_register"}
 Any form-element can be placed here
 {/ajax_form} 

Possible parameters:

  • url - URL for AJAX-query (when no URL was specified current one will be used)
  • method - query method (by default get, can be get or post)
  • params - URL-encoded parameters
  • id - form ID
  • callback - JavaScript function which will be called when query will be completed

This article originally appeared on : kpumuk.info

phpwiki - The Wiki for PHP Developers

This month it's time to look at another of those PHP applications I find useful on a daily basis. I like to use "wikis" for documentation for many of the projects I work on. Most of you are probably familiar with the term wiki, coming from the Hawaiian word for quick (wikiwiki). There are quite a few PHP-based wiki tools out there, including mediawiki (which Wikipedia uses), PmWiki and DokuWiki. In this article we will look at PhpWiki, and we'll show you how to configure and use it with your own projects!

Ward Cunningham wrote the first wiki application in 1995 (although similar software had appeared before, he was the first to apply the term "wiki" to it). Since then, wikis have exploded in popularity, as they provide a convenient way for people to collaborate, with edits being easy, and, equally important, all changes that are made are documented and tracked. The most well-known wiki is of course Wikipedia, the wiki encyclopedia. You can see a more complete list of PHP-based wikis on the Wikipedia site.

Which brings us to PhpWiki! PhpWiki's documentation is not particularly good, which should be a warning that installing a wiki is no panacea for a poorly-documented project. At the time of writing, the latest stable version is 1.3.12p1, but the home page mentions that the latest version as 1.3.11p1, and claims to have last been updated in September 2005. Setup is also a bit more finicky than some of the other applications I looked at in earlier articles. Nevertheless, I find the tool useful, and we will look at setting it up and getting it running in this month's article.

Requirements

  • A web server with PHP version 4.0.6 or greater, though of course you should not be running this old a version for security reasons. There are problems with versions from 4.3.9 and earlier which manifest if you have large installations of around 500 pages or more.
  • Perl regular expressions compiled into PHP (it is by default)
  • Database support. PhpWiki supports MySQL, PostgreSQL, Microsoft SQL Server, Oracle 8, Firebird (with PHP 5's PDO) and later version of Oracle (with PDO).
  • The PEAR DB libraries (installed by default), although PhpWiki comes with these bundled if you don't already have them, and it can also use ADODB.

Installing and configuring PhpWiki

Download the tar file, and place it in your webtree. For the purposes of this tutorial, my wiki will sit in the root directory of the greenman.co.za server. Extract the file:

tar -zxvf phpwiki-1.3.12p1.tar.gz
I suggest renaming  the directory from phpwiki-1.3.12 to simply phpwiki, or even just wiki.
mv phpwiki-1.3.12p1 wiki
You can now access  your wiki from a browser: http://greenman.co.za/wiki. Before you can do any editing,  you'll first have to configure everything.

When you first access the wiki and you haven't configured it yet, the configurator will appear (screenshot 1). This is claimed to be experimental, and has a number of minor usability issues, but it's useful for getting started quickly. The configurator page can look intimidating, as there are many, many options. Don't be put off though, as you can leave most of them with their default values. There are only a few that must be populated in order to get started. Here's what you need to change as a minimum to get your wiki working.

  • admin user
  • admin password
  • Database Type (SQL PEAR should work on any installation)
  • SQL Type (MySQL)
  • SQL User (I chose phpbuilder_wiki)
  • SQL Password (I chose phpbuilder_wiki_password)

In order for the configurator to work, it needs to be able to write to the config directory, as it attempts to create a file called config.ini. If, as is likely by default, it can't create this file, it will output the contents (screenshot 2), and you'll need to copy and paste and create the file yourself. The file must be placed in the config directory. You could also assign write permission to the directory beforehand. Perhaps the easiest alternative of all, seeing as the installation process is finicky enough to demand you work in the command line anyway, is to simply make a copy of the default config file:

cp config-dist.ini config.ini
and edit the  options above. One minor change is that you have to collate the database  authorization data into the variable DATABASE_DSN. With the options I  chose, the variable will look as follows:
DATABASE_DSN = "mysql://phpbuilder_wiki:phpbuilder_wiki_password@localhost/phpbuilder_wiki
Whichever way you  choose to configure PhpWiki, I suggest that any later changes you make get made  in the config.ini file directly. You can access the configurator again, using  your admin username and password, but you'll need to remember to re-enter passwords,  and watch out for encryption issues, making it an annoyance to use. Rather than  do that, I just go straight to the file - if you can use a text editor you'll  find it just as easy.

In this tutorial, I'll assume you're using MySQL. Specific instructions for other databases are found in the doc directory (an INSTALL file with an extension of the name of the database, e.g. INSTALL.pgsql). You'll need to already have an account with permission (such as root) to create new databases and tables, and populate them, or get your hosting company to do this for you if not.

First, create the new database. The database name must match the name you selected earlier with the configurator (I chose phpbuilder_wiki):

mysqladmin -uroot_user -proot_password create phpbuilder_wiki
Next, create a new  user with the correct permissions (I chose a user with the same name as the  database, phpbuilder_wiki,  and a password of phpbuilder_wiki_password):
mysql -uroot_user -proot_password phpbuilder_wiki
GRANT select, insert, update, delete, lock tables
 ON phpbuilder_wiki.*
 TO phpbuilder_wiki@localhost
 IDENTIFIED BY 'phpbuilder_wiki_password';
Next, create the  tables. The statements for doing this are found in the mysql-initialize.sql file in the schemas directory. Assuming that you're in the wiki directory, run the following  command, this time using the username and password created for your wiki:
mysql -uphpbuilder_wiki -pphpbuilder_wiki_password phpbuilder_wiki < schemas/mysql-initialize.sql
After all this,  you're ready to access your wiki from a browser (simply go to the wiki  directory - in my case www.greenman.co.za/wiki). The first time you access it will  display a long list of files (screenshot  3) that are the wiki's default contents. From now on, anytime you  access the wiki you'll be redirected to the home page - http://greenman.co.za/wiki/index.php/HomePage (screenshot  4).

Using phpwiki

Wikis wouldn't be popular if they weren't simple to use. Even the least technically proficient user can get started very quickly. To make a change to a page, simply press Edit, make the changes you want, then press Save. See screenshot 15 for what comes when editing the default home page. Notice that there's only plain text in the textarea, nothing fancy. If you're new to wikis, that what makes them so powerful. Anyone can edit them with almost no technical knowledge. Most wikis have a section called the SandBox, which is designed to allow people to test their editing and get to know the system. It doesn't matter if someone messes it up as it contains no critical data, and after all, it is designed for testing. In our newly-installed wiki, the whole site is basically a sandbox, so we'll stick to editing the home page for now. Add some text at the top of the page (screenshot 16) and view your changes on the home page again (screenshot 17). What could be easier?!

Of course, to make the best use of your editing potential, it helps to learn a few tricks to enable you to format the page nicely and to create links. PhpWiki makes it really simple to add basic formatting, such as bold and italics. Simply highlight the word, and click the bold or italic symbol, just like any ordinary word processor. You'll see that the highlighted text gets surrounded by some characters, and an asterisk before and after the text makes it bold (don't get confused with a single asterisk at the start of the line, which creates a bulleted list), and an underscore for italics (screenshot 18, and screenshot 19 after saving).

this *text is bold*
*bulleted item 1
*bulleted item 2
this _text is italicised_
You'll soon find  it easier to enter these special text characters as you type rather than  worrying about highlighting with the mouse, and you can then call yourself a  true wiki user. Have a look at the bottom of the edit page for more text that  doesn't appear in the shortcuts above (such as exclamation marks for a heading,  or a hash for a numbered list).

Adding a link can be done in the same way (the special character is a square bracket), but there's an even easier way. You may have noticed that words such as WikiWikiWeb and SandBox are links, though they don't have any special characters around them. The secret here is in the capitalization. If a word starts with a capital letter, and has one or more capital letters later in the word, it's automatically a link. The idea here is to combine two or more words into one page title. Try adding some text, such as TestPageOne and view the results after you've saved (screenshot 20). You'll see that the word is underlined, with a question mark after it. This means it's a link, but the page has not yet been created. Simply click on the question mark, and you're immediately editing the new page. Create the new page, but try not to make the newbie mistake of leaving the default text (Describe [TestPageOne] here.) at the top of the page.

There's more to editing. It doesn't have to be a hit and miss experience. I always preview a page before finally saving it (the page jumps back to the editing part, but the previewed page will be above that). You can also sign in in the bottom right (no authentication is necessary by default) - you may have noticed that I've been signed in if you've been viewing the screenshots. One of the advantages of this is that PhpWiki keeps a record of changes made, and it usually helps if others can see who made the change. If someone makes a change without signing in, their IP is recorded instead, so it's still theoretically possible to track them.

To view all changes made to the system, go back to the home page (by clicking on the logo), and then click RecentChanges (screenshot 21). Assuming you've been doing the same changes I have, you'll notice only one change listed, even though you've actually edited the page three times. The reason for this is that PhpWiki also takes note of the difference between a major change and a minor change. The mechanism for this is the little checkbox you may have noticed beneath the editing textarea that reads This is a minor change. It's unchecked by default when a page is created, and when a page is edited for the first time that day. If you click on the RecentEdits link (at the top of the RecentChanges page, you'll see that all three edits have been recorded. (screenshot 22)

When your wiki gets larger, you may start to find that you're not only interested in links that leave the page you're on (such as TestPageOne leading off HomePage), but also the other way around. When you're on TestPageOne, you may want to know which page(s) link to it. The answer here is provided by the BackLinks button. On any page, click BackLinks, and you'll get a list of all pages that link to that particular page. Try this on your newly created TestPageOne (screenshot 23).

Another commonly used page reveals the edit history of a page. On Wikipedia for example, the history is often as revealing as what's on the front page, especially for controversial topics in the midst of an edit war. You can see a page's history by clicking the PageHistory button (screenshot 24). There are more powerful features related to the history. As a collaboration tool, tracking changes is very important. You can see the difference between any two versions by checking the checkoxes next to those versions. Take a look at the differences between the initial and current versions of the HomePage for example (screenshot 25). You'll also see that you can easily revert to an earlier version (making post-vandalism repairs very easy).

Changing the look

Like so many Open Source applications, it's not only the coders who've contributed, but also the designers. PhpWiki comes with a number of skins. Here's a list of those bundled with PhpWiki:

To change the theme associated with the wiki, open up config.ini, and scroll down to Part Four, which lists all the available themes:

;=========================================================================
;
; Part Four:
; Page appearance and layout
;=========================================================================
 
; THEME
;
; Most of the page appearance is controlled by files in the theme
; subdirectory.
;
; There are a number of pre-defined themes shipped with PhpWiki.
; You may also create your own (e.g. by copying and then modifying one of
; stock themes.)
;
;   THEME = default
;   THEME = MacOSX
;   THEME = smaller
;   THEME = Wordpress
;   THEME = Portland
;   THEME = Sidebar
;   THEME = Crao
;   THEME = wikilens (Ratings)
;   THEME = Hawaiian
;   THEME = SpaceWiki
;   THEME = Hawaiian
;
;
; Problems:
;
;   THEME = MonoBook (WikiPedia) [experimental. MSIE problems]
;   THEME = blog     (Kubrick)   [experimental. Several links missing]
;
THEME = default
Simply change the  uncommented line (lines beginning with a semicolon are commented out) THEME = default to reflect the theme you want, for example THEME = Crao. Note that if you're  experimenting with different themes, you may be thrown by the default caching  behaviour, thinking that the themes are not working. PhpWiki by default uses LOOSE caching, which means that the page is cached until the next time it is edited  (so a theme change is only reflected after a new edit). You can change this  setting to NO_CACHE in Part One of config.ini if it's causing problems.

More configuration

Depending on the nature of your wiki, you may not want just anybody editing, or even viewing, your pages. You have quite a lot of flexibility with regards to this. Take a deeper look in the config.ini file. Part Three is what's relevant here. By default, most options are set to their least strict possibility. ALLOW_ANON_USER is set to true, so users don't have to log in to view the pages. Similarly, ALLOW_ANON_EDIT is also true, so anonymous users can make edits. Even if they do log in, ALLOW_BOGO_LOGIN is set to true, which means that no actual password authentication is performed. There are all sorts of more rigorous alternatives, from Apache authentication, IMAP authentication, LDAP authentication or external database authentication. Have a look at the documentation in the config file for more details.
There are many more options. PhpWiki is certainly flexible. You can create user groups, fine-tune the caching mechanism, implement spamassasin and captcha, persistent sessions and much, much more! Take the time to read through the configuration file carefully. You may find something that makes your life a lot easier.

Conclusion

Although PhpWiki can be finicky to install and configure when compared with other PHP applications, it's a faithful clone of the original WikiWikiWeb, and is more flexible than some of the alternatives. It's a powerful collaboration tool--enjoy using it!

Links

This article originally appeared on PHPBuilder.com.

Monday, May 26, 2008

Jelix - PHP5 Framework

General informations

Jelix is a framework for PHP5, whose objective is to ease the development of applications or Web sites of any kind.

Here is what is proposed to developers:

  • API dealing with numbers of technical aspects: data access, MVC model, templates, output format generators (HTML, XUL,…), Web services (xml-RPC, json-RPC), forms generator, CRUD, authentication, rights management, localization, etc…
  • a modular structure and an organization of the files of the project, imposing a framework and some developing standards.
  • a “layer” organization of the project: presentation, coordination, service, business, persistence.

These characteristics allow a better re-use of the code, a capitalization of know-how, a better organization in the development, leading to a better productivity.

Jelix uses to the maximum of specificities of PHP5, in order to be the lightest and most powerful possible. This is why a project based on Jelix is 100% object oriented.

Features

Original functions and characteristics

  • Modular architecture : an application can be cut out in several reusable modules.
  • Minimal guarantee on the data exchange : Jelix controls the generation of output formats according to the type of request. For example, if we have a request for a XML-RPC web service, we cannot generate HTML, the answer will be obligatorily in XML-RPC. Si it offers a certain robustness of the application in client/server communication. (Unless the developer does not use objects from Jelix, because indeed nothing prevents from making an echo of anything anywhere).
  • Generation of technical errors in specified format : thanks to the Jelix system described before, all the technical errors are returned in the format awaited by the client. For example: no HTML formatted error when client is awaiting XML-RPC or RDF response.
  • Light and evolutionary template engine (jTpl), with a syntax halfway between Smarty and PHP. A plugin system like in Smarty is also available.
  • jDao, object-relational mapping, based on the DAO design pattern (Data Access Object). Declared in XML files, automatic generation of its SQL requests , handling of security problems (SQL injection etc…).
  • Designation of files and resources by selectors, and not by physical ways, then bringing a certain independence to a module towards the installation.
  • Event system allowing module-to-module communication.
  • Overload file : it is possible to redefine some files of a module without changing the originals (DAO, templates, properties). Useful when a module is used by several applications at the same time, or to facilitate the update of a third module.

Modern functions and characteristics

Functions that we don’t find so often in frameworks:

  • Web Services : Jelix deals with analysis of the content of requests, and the generation of the response. XML-RPC and JSON-RPC are handled. Other types of services Web are completely possible (SOAP,…).
  • Handling of RESTfull : by simple implementation of an interface: one can easily define what is done after HTTP GET/POST/PUT/DELETE requests.
  • Themes system: it is possible to define several templates, each one redefining the template of modules.
  • Automatic system for URL generation and mapping : no complete URL in Jelix. The framework has the responsibility to generate urls in the templates or elsewhere, according to the configuration of URL mapping defined on actions (mod_rewrite & co).
  • PHP scripts for code generation to execute in command liner, allowing fast creation of various files of a project (module, DAO, template, controller, etc)
  • Technical cache system : almost all non PHP files of a Jelix project “are compiled” in PHP in order to improve the performances (templates, DAO, events etc.).
  • UTF-8 compliant: it's the default encoding of the framework
  • Module dedicated to unit tests: unit tests are essentials to create a reliable application. So Jelix provide a module which has an interface to launch unit tests and a simple way to create unit tests (using simpleTest)

Traditional functions and characteristics

Functions which one finds in many frameworks:

  • The architecture of the core is MVC type (Model-View-Controller). A coordinator handles the execution of an action according to the parameters in the URL. The possible actions are implemented in classes of jController type (controllers).
  • Jelix provide several output generators (jResponse objects): XHTML, CSS, ATOM, RSS, XML, RDF, XUL, XUL overlay, ZIP, PDF (from Latex source files or with TCPDF). Others formats are also possible.
  • Database access abstraction layer: jDb relies on PDO or its own classes (when PDO is not available) to access to the databases.
  • Localization: you can have your application translated in several languages. Storage of localized string is done in properties files.
  • System of authentication and rights management.
  • Use of XML: declaration of the events, DAOs etc, … That makes it possible to facilitate writing, generation and modifying these parts of a project by third-party tools (for example with JelixEclipse, an eclipse plugin), and thus to increase productivity.

How does Jelix work

  1. an HTTP request calls Jelix. Jelix creates an instance of a jRequest object which contains datas of the request. It then create an instance of your controller which corresponds to the asked action.
  2. A method in the controller is executed. It retrieves request parameters in order to know which process to run.
  3. Then the method execute business processes and retrieves eventually some results which will be used for the response
  4. The method of the controller create an instance of a jResponse object which is setup with datas or else (initialization of templates etc..).
  5. Jelix gets this jResponse object, launch the generation of the final document (html page, pdf..) and then sends it to the browser.

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

Adobe Flex

From Wikipedia, the free encyclopedia

Adobe Flex is a collection of technologies released by Adobe Systems for the development and deployment of cross platform, rich Internet applications based on the proprietary Adobe Flash platform. The initial release in March 2004 by Macromedia included a software development kit, an IDE, and a J2EE integration application known as Flex Data Services. Since Adobe acquired Macromedia in 2005, subsequent releases of Flex no longer require a license for Flex Data Services, which has become a separate product rebranded as LiveCycle Data Services.

In February 2008, Adobe released the Flex 3 SDK under the open source Mozilla Public License. Adobe Flash Player, the runtime on which Flex applications are viewed, and Flex Builder, the IDE used to build Flex applications, remain proprietary.

Overview

Traditional application programmers found it challenging to adapt to the animation metaphor upon which the Flash Platform was originally designed. Flex seeks to minimize this problem by providing a workflow and programming model that is familiar to these developers. MXML, an XML-based markup language, offers a way to build and lay out graphic user interfaces. Interactivity is achieved through the use of ActionScript, the core language of Flash Player that is based on the ECMAScript standard.

The Flex SDK comes with a set of user interface components including buttons, list boxes, trees, data grids, several text controls, and various layout containers. Charts and graphs are available as an add-on. Other features like web services, drag and drop, modal dialogs, animation effects, application states, form validation, and other interactions round out the application framework.

In a multi-tiered model, Flex applications serve as the presentation tier. Unlike page-based HTML applications, Flex applications provide a stateful client where significant changes to the view don't require loading a new page. Similarly, Flex and Flash Player provide many useful ways to send and load data to and from server-side components without requiring the client to reload the view. Though this functionality offered advantages over HTML and JavaScript development in the past, the increased support for XMLHttpRequest in major browsers has made asynchronous data loading a common practice in HTML-based development too.

Technologies that are commonly compared to Flex include OpenLaszlo, Ajax, XUL, JavaFX and Windows Presentation Foundation technologies such as Silverlight.

Macromedia Flex Server 1.0 and 1.5

Macromedia targeted the enterprise application development market with its initial releases of Flex 1.0 and 1.5. The company offered the technology at a price around US$15000 per CPU. Required for deployment, the J2EE application server compiled MXML and ActionScript on-the-fly into Flash applications (binary SWF files). Each server license included 5 licenses for the Flex Builder IDE.

Adobe Flex 2

Adobe significantly changed the licensing model for the Flex product line with the release of Flex 2. The core Flex 2 SDK, consisting of the command-line compilers and the complete class library of user interface components and utilities, was made available as a free download. Complete Flex applications can be built and deployed with only the Flex 2 SDK, which contains no limitations or restrictions compared to the same SDK included with the Flex Builder IDE.

Adobe based the new version of Flex Builder on the open source Eclipse platform. The company released two versions of Flex Builder 2, Standard and Professional. The Professional version includes the Flex Charting Components library.

Enterprise-oriented services remain available through Flex Data Services 2. This server component provides data synchronization, data push, publish-subscribe and automated testing. Unlike Flex 1.0 and 1.5, Flex Data Services is not required for the deployment of Flex applications.

Coinciding with the release of Flex 2, Adobe introduced a new version of the ActionScript programming language, known as Actionscript 3, reflecting the latest ECMAScript specification. The use of ActionScript 3 and Flex 2 requires version 9 or later of the Flash Player runtime. Flash Player 9 incorporated a new and more robust virtual machine for running the new ActionScript 3.

Flex was the first Macromedia product to be re-branded under the Adobe name.

Adobe Flex 3

On April 26, 2007 Adobe announced their intent to release the Flex 3 SDK (which excludes the Flex Builder IDE and the LiveCycle Data Services) under the terms of the Mozilla Public License.[1] Adobe released the first beta of Flex 3, codenamed Moxie, in June 2007. Major enhancements include integration with the new versions of Adobe's Creative Suite products, support for AIR (Adobe's new desktop application runtime), and the addition of profiling and refactoring tools to the Flex Builder IDE.

In October 2007, Adobe released the second beta of Flex 3.
On December 12, 2007, Adobe released the third beta of Flex 3.
On February 25, 2008, Adobe released Flex 3 and Adobe AIR 1.0.

Adobe Flex 4

Adobe has announced that Flex 4.0 (code named Gumbo) will be released in 2009. Even though this announcement has been made, the product plan has yet to be completed.

Some themes that have been mentioned by Adobe that will be incorporated into Flex 4 are as follows:

  • Design in Mind: The framework will be designed for continuous collaboration between designers and developers.
  • Accelerated Development: Be able to take application development from conceptual to reality quickly.
  • Horizontal Platform Improvements: Compiler performance, language enhancements, BiDi components, enhanced text. (Speculation derived from Adobe Systems)
  • Broadening Horizons: Finding ways to make a framework lighter, supporting more deployment runtimes, runtime MXML. (Speculation derived from Adobe Systems)

Flex 4 milestones: (Speculation derived form Adobe Systems)

  • Scope determined, April 2008
  • Beta 1, late 2008
  • 4.0 final, 2009

LiveCycle Data Services

LiveCycle Data Services (previously called Flex Data Services) is a server-side complement to the main Flex SDK and Flex Builder IDE and is part of a family of server-based products available from Adobe. Deployed as a Java EE application, LiveCycle Data Services adds the following capabilities to Flex applications:

  • Remoting, which allows Flex client applications to invoke methods on Java server objects directly. Similar to Java remote method invocation (RMI), remoting handles data marshalling automatically and uses a binary data transfer format.
  • Messaging, which provides the "publish" end of the "publish/subscribe" design pattern. The Flash client can publish events to a topic defined on the server, subscribe to events broadcast from the message service. One of the common use cases for this is real-time streaming of data, such as financial data or system status information.
  • Data management services, which provides a programming model for automatically managing data sets that have been downloaded to the Flex client. Once data is loaded from the server, changes are automatically tracked and can be synchronized with the server at the request of the application. Clients are also notified if changes to the data set are made on the server.
  • PDF document generation, providing APIs for generating PDF documents by merging client data or graphics with templates stored on the server.

BlazeDS

Previously available only as part of Adobe LiveCycle Data Services ES, Adobe is announcing its plans to contribute the proven BlazeDS technologies to the community under the LGPL v3. BlazeDS gives the rapidly growing Adobe developer community free access to the powerful remoting and messaging technologies developed by Adobe.

Concurrent with this pre-release of BlazeDS, Adobe is publishing the AMF binary data protocol specification, on which the BlazeDS remoting implementation is based, and is committed to partnering with the community to make this protocol available for every major server platform. The source code will be available for download early 2008.

Flex and ColdFusion

Flex 2 offers special integration with ColdFusion MX 7. The ColdFusion MX 7.0.2 release adds updated Flash Remoting to support ActionScript 3, a Flex Data Services event gateway, and the Flex Data Services assembler. Flex Builder 2 also adds extensions for ColdFusion providing a set of wizards for RAD Flex development. A subset of Flex 1.5 is also embedded into ColdFusion MX 7 middleware platform, for use in the ColdFusion Flash forms feature. It is possible to use this framework to write rich internet applications, although its intended purpose is for rich forms only.

Flex Application Development Process

Everything below is directly sourced from the help file in version 2.0 Beta 3:

  • Define an application interface using a set of pre-defined components (forms, buttons, and so on)
  • Arrange components into a user interface design
  • Use styles and themes to define the visual design
  • Add dynamic behavior (one part of the application interacting with another, for example)
  • Define and connect to data services as needed
  • Build the source code into an SWF file that runs in the Flash Player

Release history

  • Flex 1.0 - March 2004
  • Flex 1.5 - October 2004
  • Flex 2.0 (Alpha) - October 2005
  • Flex 2.0 Beta 1 - February 2006
  • Flex 2.0 Beta 2 - March 2006
  • Flex 2.0 Beta 3 - May 2006
  • Flex 2.0 Final- June 28, 2006
  • Flex 2.0.1 - January 5, 2007
  • Flex 3.0 Beta 1 - June 11, 2007
  • Flex 3.0 Beta 2 - October 1, 2007
  • Flex 3.0 Beta 3 - December 12, 2007
  • Flex 3.0 - February 25, 2008

Notable sites using Flex

Notable sites using Flex include:

See also

CodeIgniter

CodeIgniter - Open source PHP web application framework

CodeIgniter is an Application Framework

CodeIgniter is a toolkit for people who build web application using PHP. Its goal is to enable you to develop projects much faster than you could if you were writing code from scratch, by providing a rich set of libraries for commonly needed tasks, as well as a simple interface and logical structure to access these libraries. CodeIgniter lets you creatively focus on your project by minimizing the amount of code needed for a given task.

CodeIgniter is Free

CodeIgniter is licensed under an Apache/BSD-style open source license so you can use it however you please. For more information please read the license agreement.

CodeIgniter Runs on PHP 4

CodeIgniter is written to be compatible with PHP 4. Although we would have loved to take advantage of the better object handling in PHP 5 since it would have simplified some things we had to find creative solutions for (looking your way, multiple inheritance), at the time of this writing PHP 5 is not in widespread use, which means we would be alienating most of our potential audience. Major OS vendors like RedHat are moving slowly to support PHP 5, and they are unlikely to do so in the short term, so we felt that it did not serve the best interests of the PHP community to write CodeIgniter in PHP 5.

Note: CodeIgniter will run on PHP 5. It simply does not take advantage of any native features that are only available in that version.

CodeIgniter is Light Weight

Truly light weight. The core system requires only a few very small libraries. This is in stark contrast to many frameworks that require significantly more resources. Additional libraries are loaded dynamically upon request, based on your needs for a given process, so the base system is very lean and quite fast.

CodeIgniter is Fast

Really fast. We challenge you to find a framework that has better performance than CodeIgniter.

CodeIgniter Uses M-V-C

CodeIgniter uses the Model-View-Controller approach, which allows great separation between logic and presentation. This is particularly good for projects in which designers are working with your template files, as the code these file contain will be minimized. We describe MVC in more detail on its own page.

CodeIgniter Generates Clean URLs

The URLs generated by CodeIgniter are clean and search-engine friendly. Rather than using the standard "query string" approach to URLs that is synonymous with dynamic systems, CodeIgniter uses a segment-based approach:

www.your-site.com/news/article/345

Note: By default the index.php file is included in the URL but it can be removed using a simple .htaccess file.

CodeIgniter Packs a Punch

CodeIgniter comes with full-range of libraries that enable the most commonly needed web development tasks, like accessing a database, sending email, validating form data, maintaining sessions, manipulating images, working with XML-RPC data and much more.

CodeIgniter is Extensible

The system can be easily extended through the use of plugins and helper libraries, or through class extensions or system hooks.

CodeIgniter Does Not Require a Template Engine

Although CodeIgniter does come with a simple template parser that can be optionally used, it does not force you to use one. Template engines simply can not match the performance of native PHP, and the syntax that must be learned to use a template engine is usually only marginally easier than learning the basics of PHP. Consider this block of PHP code:

<ul>

<?php foreach ($addressbook as $name):?>

<li><?=$name?></li>

<?php endforeach; ?>

</ul>

Contrast this with the pseudo-code used by a template engine:

<ul>

{foreach from=$addressbook item="name"}

<li>{$name}</li>

{/foreach}

</ul>

Yes, the template engine example is a bit cleaner, but it comes at the price of performance, as the pseudo-code must be converted back into PHP to run. Since one of our goals is maximum performance, we opted to not require the use of a template engine.

CodeIgniter is Thoroughly Documented

Programmers love to code and hate to write documentation. We're no different, of course, but since documentation is as important as the code itself, we are committed to doing it. Our source code is extremely clean and well commented as well.

CodeIgniter has a Friendly Community of Users

Our growing community of users can be seen actively participating in our Community Forums.

click here for the CodeIgniter User Guide

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.