AlphaFramework.org Date Added: 2011-03-17 Last Updated: 2012-01-17 Revision: 5
Modern web sites are rarely used to serve up static content, but instead are usually expected to serve up dynamic content that can be delivered to the user in a variety of formats. Web sites are expected by end users to be interactive: allowing them to submit comments to a blog entry, populate shopping carts with items, or search the website for particular content using a search engine. Once a web site contains features like these, it is usually referred to as a web application.
A web application framework is a set of common computer code components that can be reused on multiple web applications. The components are designed to solve common problems in a standard, predictable, and tested way. By using a web application framework, we can produce complex web applications much quicker than in the past when each new component had to be programmed separately, instead we can use the existing framework components in new projects to meet as many requirements as possible, and then concentrate on adding in the remaining features which are unique to that application.
The Alpha Web Framework (or simply Alpha) was designed to be an easy to use web application framework, which is capable of supporting a wide variety of web applications. The key principal of the Alpha design ethos is to keep it simple, for example by favouring convention over configuration to avoid the need for a large upfront configuration effort.
The core of Alpha is designed to support only those key elements of a web application: the data model, the presentation views, and finally the controlling logic. These three layers are often called the Model View Controller, or MVC.
The model represents the business model that your application is trying to represent. Each element of the model is referred to as a business object. A business object represents something from the real world which you want to track in your system, for example a hotel would have a reservation business object, a bank would have a mortgage application business object, and an e-commerce system would have a shopping cart business object. The model layer of Alpha handles all of the database logic for creating, reading, updating, and deleting these business objects for you.
The view represents the varied ways which you present your business object data to the end users. Typically this will be in the form of HTML web pages, however Alpha supports many other formats such as PDF and RSS news feeds. Web services support will also be included in later versions. Using a process called scaffolding, Alpha can generate these views for you automatically from your business objects, enabling you to then customise those views to suit your requirements later on in the project. The scaffolding process gives you a major head start in the early phase of your project.
The controller layer is where all of the business logic of your application resides; it is in the controller code that things happen. Think of a controller as a middle man: it interacts with the model to populate business objects, which it then feeds into a view which renders the business data to the end user. By default, Alpha includes a powerful administration back-end which includes lots of useful controllers for listing business objects, creating new business objects, editing and deleting old business objects, and finally viewing other pertinent administration information such as test results and error logs. All of the existing controllers supplied with Alpha can be extended to create custom controllers to meet your requirements.
While the MVC components are the core of Alpha, there are many other elements of the framework which you should find useful on any web application project. Here are some of the highlights included in the 1.0 release:
There are many, many more features planned for Alpha in the 1.0 release, and other releases beyond that, but hopefully the above list will give you some idea of the scope of this framework. Please see our feature roadmap for more details.
Alpha is under constant active development, with new features being added all of the time, while existing features are tested and tweaked to improve performance and reliability. The Alpha Framework is designed to make web application development fast and easy: by encapsulating all common functionality in the framework, you are freed up to concentrate on those unique elements in your project that require your attention at an earlier stage of the development.
Alpha is designed with robustness and security in mind from day one: advanced security features are part of the core framework, not some optional components to be added in later. Carrying out business on the Internet is a complex and problematic affair, to ease these concerns a strong level of robustness and security is a given.
Alpha is released under the Berkley Standard Distribution (BSD) open source license, which enables you to use Alpha on open source projects and commercial projects alike. We believe that Alpha is useful to everyone involved in building web applications, so decided to release it under an unrestrictive license.
We encourage you to use Alpha in all of your future web projects!
The following software components are required to use Alpha:
| Software | Minimum Version | Link |
|---|---|---|
| PHP | 5.2 | http://www.php.net/ |
| Apache2* | 2.0 | http://httpd.apache.org/ |
| MySQL | 4.1 | http://www.mysql.com/ |
* Note that the mod_rewrite Apache module is required to use fancy URLs, along with support for .htaccess files to enable per-folder Apache directives.
The following software libraries are used by Alpha to provide additional functionality:
| Software | Tested Version | Link | Required by Alpha? | Included with Alpha? | Usage |
|---|---|---|---|---|---|
| TCPDF | 4.6.003 | http://www.tcpdf.org/ |
No | Yes | Generates PDF versions of articles in the Alpha CMS. |
| PHP Markdown Extra | 1.1.2 | http://michelf.com/projects/php-markdown/ |
Yes | Yes | Provides a wiki syntax parser for the Alpha CMS. |
| JQuery | 1.3.2 | http://jquery.com/ |
Yes | Yes | Used in the Javascript routines throughout Alpha. |
| JQuery UI | 1.7.2 | http://docs.jquery.com/UI |
Yes | Yes | Used for widgets throughout Alpha to provide a more pleasant user experience. |
| JQuery Context Menu Plugin | 1.00 | http://abeautifulsite.net/notebook/80 |
No | Yes | Can be used at an application level to provide context menus. |
| jdMenu | 1.4.1 | http://jdsharp.us/ |
Yes | Yes | Provides the top menu in the admin interface. |
| PEAR::File_Find | - | http://pear.php.net/package/File_Find |
No | No | Used in the software metrics package. |
| PEAR::PHPUnit | 3.2.9 | http://www.phpunit.de/ |
No | Yes | Used for executing Alpha's unit tests. |
| GeSHi | 1.0.7.4 | http://qbnz.com/highlighter/ |
No | No | A code syntax highlighter that can be used in the Alpha CMS. |
| markItUp | 1.1.4 | http://markitup.jaysalvat.com/ |
Yes | Yes | Provides a nice interface for editing Markdown content in the Alpha CMS. |
Note that these installation steps are carried out from the Linux command line, which is a common platform for web servers. The steps required for other systems like Windows will differ somewhat.
You will need at least one new MySQL database for Alpha (two if you want to be able to run the included unit tests). Begin by logging into your MySQL database server, then create a new database:
[johnc@redhat ~]# mysql -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 1544 Server version: 5.0.37 Source distribution Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql> create database contacts; Query OK, 1 row affected (0.00 sec) mysql> use contacts; Database changed mysql>
Here we have created a new database called contacts which we will use for our sample application that we will cover later.
Download the latest version of Alpha from here, then extract it to a directory under Apache (in this example, Apache is serving files under /var/www/html):
[johnc@redhat ~]$ mkdir /var/www/html/contacts [johnc@redhat ~]$ unzip alpha-1.0.zip -d /var/www/html/contacts/
Now when you list the contents of the /var/www/html/contacts directory it should look something like this:
[johnc@redhat ~]$ ls -l /var/www/html/contacts/ total 16 drwxrwxr-x 14 johnc johnc 4096 2011-12-03 16:13 alpha drwxrwxr-x 2 johnc johnc 4096 2011-12-03 16:13 config drwxrwxr-x 2 johnc johnc 4096 2011-12-03 16:13 css -rw-rw-r-- 1 johnc johnc 2491 2011-12-03 15:19 index.php
Next up, you will need to change the ownership on your applications files to the user account that Apache runs under:
[johnc@redhat html]$ su Password: [root@redhat html]# chown apache -Rf /var/www/html/contacts/ [root@redhat html]# ls -l /var/www/html/contacts/ total 16 drwxrwxr-x 14 apache johnc 4096 2011-12-03 16:13 alpha drwxrwxr-x 2 apache johnc 4096 2011-12-03 16:13 config drwxrwxr-x 2 apache johnc 4096 2011-12-03 16:13 css -rw-rw-r-- 1 apache johnc 2491 2011-12-03 15:19 index.php
If you list the contents of the /var/www/html/contacts/config directory in your application, you will see the following files:
[johnc@redhat ~]$ ls -l /var/www/html/contacts/config/ total 28 -rw-rw-r-- 1 apache johnc 5278 2011-12-03 15:19 dev.ini -rw-rw-r-- 1 apache johnc 5279 2011-12-03 15:19 pro.ini -rw-rw-r-- 1 apache johnc 102 2011-12-03 15:19 servers.ini -rw-rw-r-- 1 apache johnc 5278 2011-12-03 15:19 test.ini
The servers.ini file lists the server host names for each of the three server environments (development, production, and test). The contents of the file looks like this:
; The server names for the three environments dev = localhost pro = mywebsite.com test = testserver
It is important that you set these values to match the real server names for each environment, as Alpha will dynamically use these values to figure out which environment it is running under, and then load the corresponding dev.ini, pro.ini, or test.ini file which contains the actual application settings.
For now we will not worry about production or test, and will just concentrate on getting a developer environment up and running on localhost. Open up the dev.ini file, and ensure that the following values are set correctly (you can leave all other values set to their defaults for now):
| Setting | Description |
|---|---|
| sysURL | The root HTTP URL of you application, e.g. http://localhost/contacts/ |
| sysRoot | The root file path to your application, e.g. /var/www/html/contacts/ |
| sysDB | The name of the main MySQL database for the application, e.g. contacts |
| sysDBUsername | The MySQL username to access the database (will need create table permissions on sysDB). |
| sysDBPassword | The password for sysDBUsername to connect to the database. |
| sysDBHost | The host name of the MySQL database server, e.g. localhost. |
| sysTitle | The name of the application to display to end users, e.g. Alpha Contacts Application. |
| sysLogFile | The absolute path to the main log file for the application, e.g. /var/www/html/contacts/logs/alpha.log. |
| sysQSKey | A random string to use as an encryption key when encrypting/decrypting secure URLs. A keyboard bash of less than 24 characters is fine. |
Alpha comes with a convenient installation controller that automatically creates all of the remaining required folders, the database tables and indexes, as well as a default administration account for you to login with. You can now invoke the installation controller by accessing the root of your web application with a web browser, for example http://localhost/contacts/. Note that the first thing you will see is a login screen, here you should enter the username (email address) and password in the sysInstallUsername and sysInstallPassword settings in the dev.ini file.
Alpha will then proceed to create all of the remaining required directories and the database tables. The screen will display the output of these operations like so (any errors will also be displayed):
To confirm that the directories have been created, list the contents of your contacts application directory:
[johnc@redhat ~]$ ls -l /var/www/html/contacts/ total 40 drwxrwxr-x 14 apache johnc 4096 2011-12-03 16:13 alpha drwxrw-rw- 2 apache apache 4096 2011-12-03 19:41 attachments drwxrw-rw- 6 apache apache 4096 2011-12-03 19:41 cache drwxrwxr-x 3 apache johnc 4096 2011-12-03 19:49 config drwxrw-rw- 2 apache apache 4096 2011-12-03 19:41 controller -rw-rw-r-- 1 apache johnc 2492 2011-12-03 19:43 index.php drwxr--r-- 2 apache apache 4096 2011-12-03 19:41 logs drwxrw-rw- 2 apache apache 4096 2011-12-03 19:41 model drwxrw-rw- 2 apache apache 4096 2011-12-03 19:41 tasks drwxrw-rw- 2 apache apache 4096 2011-12-03 19:41 view
To confirm that the database tables have been created, log back into your database and issue the following SQL statements:
[johnc@redhat ~]$ mysql -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 26 Server version: 5.0.37 Source distribution Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql> use contacts; Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed mysql> show tables; +--------------------+ | Tables_in_contacts | +--------------------+ | Article | | ArticleComment | | ArticleVote | | BadRequest | | BlacklistedClient | | DEnum | | DEnumItem | | Person | | Person2Rights | | Rights | | Sequence | | Tag | +--------------------+ 12 rows in set (0.00 sec) mysql>
As you can see, Alpha has created all of the required database tables for each business object in the system automatically for you. Now if you go back to your web browser and scroll to the bottom of the installation screen, you will see a link to the Alpha administration back-end. Clicking on this link will bring you to a screen that looks like this:
The first thing that you are going to want to do here is change the password of your admin account from the default value of alpha_admin (as per the sysInstallPassword setting in dev.ini) to something more secure. Click on the list all button on the row for PersonObject, then click the edit button on the only record in the list. You should see something like this:
To change the password, overwrite the existing value in the password text field and click save. Now click on the home button in the administration bar to go to the root of your web application. You should now see a screen that looks like this:
It is at this stage that we can now start to think about building an application using Alpha.
As stated previously, Alpha is based around the model-view-controller pattern. In this section we will build a very simple contacts application that contains contact objects with some common attributes. Here is the source code for our contact class:
<?php
require_once $config->get('sysRoot').'alpha/model/AlphaDAO.inc';
class ContactObject extends AlphaDAO {
protected $firstName;
protected $lastName;
protected $email;
protected $notes;
protected $dataLabels = array("OID"=>"Contact ID#","firstName"=>"First Name","lastName"=>"Last Name","email"=>"Email", "notes"=>"Notes");
const TABLE_NAME = 'Contact';
public function __construct() {
// ensure to call the parent constructor
parent::__construct();
$this->firstName = new String();
$this->lastName = new String();
$this->email = new String();
$this->email->setRule(AlphaValidator::REQUIRED_EMAIL);
$this->email->setHelper('Please enter a valid e-mail address for this contact!');
$this->notes = new Text();
}
}
?>
As you can see, our ContactObject class extends the AlphaDAO (Alpha Data Access Object) class in Alpha. It is this class that contains all of the database interactions methods in Alpha, such as load(), save(), and delete(). The ContactObject then has a number of common contact attributes (name, email etc., you can add more if you like), which are then defined as data types in the constructor using Alpha's built in data types. The purpose of these data types is to enable Alpha to choose the correct field type in the MySQL database to store the data in, and also to avail of built-in validation and widgets in Alpha when handling more complex data types like dates, enums, and sequences (see the API documentation for the alpha--model--types package for a list of all of the available types).
The TABLE_NAME constant is the name of the database table in MySQL that will be used to store the ContactObject instances for us, you will see later how Alpha will create this for us.
The email field is a little special here as we are assigning it a validation regular expression from the AlphaValidator class (check the API documentation for this class to see what other options are available), which means that Alpha will apply a validation rule on the client side (Javascript) and the server side (PHP) to ensure that the value entered here is a valid email address. We also set some helper text to help the user to understand the validation requirements.
Now take this code and save it into a new file in the following location: /var/www/html/contacts/model/ContactObject.inc
Now log back into the administration back-end (http://localhost/contacts/alpha/service/), and you will now see that Alpha has detected the new ContactObject class, and is rendering a new row to handle it:
In the ContactObject row, click on the button to create the Contact table. Alpha will then display the status of this operation:
You can now make use of the scaffolding feature in Alpha to immediately create contacts in the database. Click on the create new button in the ContactObject row, you will now get a form like this for creating a new contact (note the validation error message when you try to leave the required e-mail field empty):
There is also a list screen...
...a view screen...
...and an edit screen which looks just like the screen for creating the contact. In the next section, we will look at changing the look of these screens at the view layer.
Next up, we will create a custom view class for the ContactObject. Create the file /var/www/html/contacts/view/ContactView.inc with the following code:
<?php
require_once $config->get('sysRoot').'model/ContactObject.inc';
require_once $config->get('sysRoot').'alpha/view/AlphaView.inc';
class ContactView extends AlphaView {
public function listView($fields=array()) {
// the form action
$fields['formAction'] = $_SERVER['REQUEST_URI'];
$fields['colCount'] = 2;
$html = '';
$html .= '<tr>';
$html .= ' <th>'.$this->BO->getDataLabel('firstName').'</th>';
$html .= ' <th>'.$this->BO->getDataLabel('lastName').'</th>';
$html .= '</tr><tr>';
$fields['formHeadings'] = $html;
$html = '';
$html .= ' <td> '.$this->BO->get('firstName').'</td>';
$html .= ' <td> '.$this->BO->get('lastName').'</td>';
$html .= '</tr>';
$fields['formFields'] = $html;
// View button
if(strpos($_SERVER['REQUEST_URI'], '/tk/') !== false) {
$button = new Button("document.location = '".FrontController::generateSecureURL('act=Detail&bo='.get_class($this->BO).'
&oid='.$this->BO->getOID())."';", 'View', 'viewBut');
$fields['viewButton'] = $button->render();
}else{
$button = new Button("document.location = '".$this->BO->get('URL')."';", 'View', 'viewBut');
$fields['viewButton'] = $button->render();
}
$html = '';
// render edit and delete buttons for admins only
if (isset($_SESSION['currentUser']) && $_SESSION['currentUser']->inGroup('Admin')) {
$html .= '';
$button = new Button("document.location = '".FrontController::generateSecureURL('act=Edit&bo='.get_class($this->BO)."
&oid=".$this->BO->getOID())."'", "Edit", "editBut");
$html .= $button->render();
$html .= '';
$js = "$('#dialogDiv').text('Are you sure you wish to delete this item?');
$('#dialogDiv').dialog({
buttons: {
'OK': function(event, ui) {
$('#deleteOID').attr('value', '".$this->BO->getOID()."');
$('#deleteForm').submit();
},
'Cancel': function(event, ui) {
$(this).dialog('close');
}
}
})
$('#dialogDiv').dialog('open');
return false;";
$button = new Button($js, "Delete", "deleteBut");
$html .= $button->render();
}
$fields['adminButtons'] = $html;
// buffer security fields to $formSecurityFields variable
$fields['formSecurityFields'] = $this->renderSecurityFields();
$this->loadTemplate($this->BO, 'list', $fields);
}
}
The above code is based on the AlphaView::listView() method from the parent class which it overrides. This custom version of the method only includes the firstName and lastName attributes in the list view, rather than all of the attributes which Alpha will do by default. Here is the updated view:
Of course you can do many further edits this way, as well as overriding the AlphaView::creatView(), AlphaView::editView(), and AlphaView::detailedView() methods from the parent with your custom versions, which Alpha will use preferentially when they exist. Another way to make changes to the views is by overriding the HTML templates in the ../alpha/view/templates directory. Let us try this now with the list template: create a file named /var/www/html/contacts/view/templates/ContactObject/list.phtml containing the following code (note you will have to create the /var/www/html/contacts/view/templates/ContactObject folder first):
<h2><?= $firstName ?> <?= $lastName ?></h2>
<form action="<?= $formAction ?>" method="POST">
<table class="list_view">
<?= $formHeadings ?>
<?= $formFields ?>
<tr><td colspan="<?= $colCount ?>" align="center">
<?= $viewButton ?>
<?= $adminButtons ?>
</td></tr>
<?= $formSecurityFields ?>
</table>
</form>
This code is a copy of the default list template, but we have added a new h2 tag which outputs the combined first and last names of the contact listed. Here is the rendered result:
As you can see, Alpha offers you a lot of flexibility in terms of how and where you can change the default views to suit your application.
You can also override any of the default Create, Edit, Detail, or ListAll controllers with your own custom versions. Once again Alpha is smart enough to auto-detect your custom ones and load them, provided that they are placed in your application's /controller directory and have the name CreateClassName.php, EditClassName.php, ListClassName.php, or ViewClassName.php. For example, if we want to define a custom CreateContact controller, create the file /var/www/html/contacts/controller/CreateContact.php with the following code:
<?php
// include the config file
if(!isset($config)) {
require_once '../alpha/util/AlphaConfig.inc';
$config = AlphaConfig::getInstance();
}
require_once $config->get('sysRoot').'alpha/controller/Create.php';
require_once $config->get('sysRoot').'alpha/controller/AlphaControllerInterface.inc';
class CreateContact extends Create {
public function doGET($params) {
echo '<h2>Custom create contact that just outputs the provided params</h2>';
echo '<pre>'.print_r($params, true).'</pre>';
}
}
?>
Now when you go to create a contact object, you will now see that the custom controller is loaded rather than the default create contact screen that Alpha generated for us automatically earlier:
Right now each controller in Alpha is expected to support only a doGET and doPOST method, however we will also add in other HTTP verbs like doPUT, doDELETE, and doHEAD in the future as we move Alpha towards supporting the REST design pattern.
One final note is that if you want to link to the CreateContact controller from outside of the administration interface, rather than using the encrypted query strings which that interface uses you can instead use this much friendlier URL structure:
http://localhost/contacts/CreateContact
To return to the administration interface at any time, load the following URL into your browser and enter in your administrator username and password:
[sysURL]alpha/service/
e.g.
http://localhost/contacts/alpha/service/
The following API documentation was generated automatically from the Alpha source code using the excellent PHPDocumentor
tool:
| Version | Link |
|---|---|
| 1.1 | http://www.alphaframework.org/alpha/docs/api |
We have big plans for Alpha. Please see our roadmap for a detailed outline of our current and planned features, along with release estimates, and follow our daily progress on Twitter
.
Tags: alpha framework frameworks interactive blog populate carts solve predictable quicker programmed ethos favouring hotel bank handles database updating html pdf rss customise scaffolding controller interacts renders administration controllers listing logs mvc highlights locking sql tables mysql span rolled abort tagged validation validated cut encryption optionally encrypt authorization cms neat rendered caching rendering voting tweaked encapsulating freed earlier robustness license berkley unrestrictive started php apache htaccess directives dependencies libraries tcpdf markdown wiki syntax parser javascript routines ui jquery widgets pleasant plugin menus admin metrics phpunit executing tests highlighter jaysalvat linux windows differ logging root commands buffer extract served mkdir unzip ls johnc config css index ownership su chown dev ini environments localhost mywebsite testserver dynamically http sysdbusername contacts string bash convenient indexes login invoke cache statements completion column startup articlecomment articlevote badrequest blacklistedclient denum denumitem rows clicking personobject contactobject alphadao const constructor interactions dates enums sequences api instances assigning expression helper screens contactview alphaview frontcontroller render buttons admins overrides edits overriding preferentially templates outputs flexibility override alphaconfig createcontact echo loaded verbs doput dodelete dohead encrypted strings friendlier phpdoc outline estimates
Article URL: http://www.alphaframework.org/article/Documentation
Title: Documentation
Author: John Collins
Copyright © 2012, the above named author. All rights reserved.