Share your knowledge and create a knowledgebase.

Archive for June, 2008


Symfony 1.1 released with interesting features

Jun 30, 2008 Author: Ashish | Filed under: Frameworks

Now the day has come to celebrate the immediate availability of the long awaited 1.1 stable release of the symfony framework!

  • The new architecture of symfony is more configureable and decoupled, allowing you to use or replace part of the framework very easily,
  • The new object-oriented form framework makes form creation and reuse a breeze,
  • The brand new task system allows to quicly make extensible batch scripts and command line utilities,
  • Symfony has now a decent YAML parser, with verbose error reporting,
  • The new plugin manager is now compatible with the PEAR standard API, handles plugins dependencies, and provides options for a better control on what you install,
  • The formats handling system can make your app behave and respond differently whether an iPhone, a bot, or a browser is requesting it,
  • The Propel 1.2 ORM is now bundled as a plugin, which means you can very easily switch to Doctrine or even to Propel 1.3 if you prefer,
  • The bundled sfCompat10Plugin will ensure that your 1.0 based projects will still work after having upgraded to 1.1!
  • The routing is now cached, so you can expect a significant performance boost when you got plenty of routes in your app. Also, the routing class is no more a singleton so you can now extend and reference it easily to fit your needs,
  • Even if that’s not really a feature, more than 8,500 unit and functional tests guarantee the overall stability of the framework codebase. We doubled the number of tests between 1.0 and 1.1!

All these can add great improvements in your development efforts.

Next big programming language feature after closures

Jun 30, 2008 Author: Ashish | Filed under: Frameworks

Closures are the current hot feature for programming languages. The inclusion of closures in Java appears to be around the corner, and the C++ committee has recently voted on closures in the upcoming C++ 0x standard.

The introduction of closures into many mainstream languages indicate to me that the logicial next big features is going to be primitive aggregate operations. Those are operations that operate on collections such as lists or arrays.

Closures, are anonymous functions created at run-time which can refer to variables that are visible where the function is declared.

Closures are especially useful when performing operations over elements in a collection. The most common collection operations (aggregate operations) in functional programming are map, filter,Ā fold, and unfold operations.

A map operation transforms a list into a new same-sized list by applying a transformation function (such asĀ a closure) to each element in the original list. A common example of a map operation is when performing a vector scaling operation.

A filter operation creates a list from another list usingĀ only those items for which a predicate function returns true.

The fold operationĀ combinesĀ values in a listĀ using a binary function and an initial value. AĀ summation function is a simple example of a fold operation.

The unfold operation creates a list from an initial value and by successively applying a generator function, until a terimination predicate returns true.

The introduction of closures into C++ and Java make aggregate operations (operations that operate on collections) easier to write and will make their usage more frequent.

Aggregate operations like unfold, fold, filter,Ā and “map” have the characteristic that they can be combined allowing significant reduction in the number of intermediate operations and data-structures created. This technique is called deforestation and is well-known when applied to pure functional programming languages such as Haskell.

In order for a C++ or Java compiler to take full-effect of deforestation, the compiler would need to know when a particular aggregate operation is occuring and whether or not there are side-effects. This is a very hard task for a compiler, unless the language has a predefined notion of aggregate operation.

Providing aggregate operations directly in programming languages have the additional advantage that it is easier for compilers to generate code that exploits multiple cores.

A testament of how effective aggregate operations is demonstrated by the success of the array-oriented languages APL, J, and K. These are usually implemented with interpreters which have excellent performance characteristics.

There are already some basic predefined operations on arrays in the Java virtual machine (JVM) and Common Intermediate Language (CIL) [Edit: replaced CLR with CIL, I meant to refer to .NET byte-code] for indexing and computing the size. The introduction of more sophisticated aggregate operations like map, filter, fold and unfold would be a logical extension to the CLR and the JVM.Ā The performanceĀ benefits would not only beĀ significant for single processors but there wouldĀ also be benefit forĀ code running on multiple processirs.

23+ Impressive Tools for Faster Javascript/Ajax Development

Jun 26, 2008 Author: Ashish | Filed under: JavaScript

Javascript applications are still one of the most complex issues when it comes to web-development. Many tools and applications could make your developing life pretty fast and simple. Today we wanted to share with you a wide range of tools and applications that could really help you build, test and debug Javascript and Ajax applications. Let us know your experience with the tools listed here or others that are not.
1-Roar - Notifications (v1.0) Roar is a notification widget that streamlines incoming messages, such as updates or errors, without distracting the user from their browser experience or breaking their work-flow by displaying obtrusive alerts.

javascript ajax tools


2-Damn It DamnIT is a free service that emails you when a user encounters a JavaScript error in your webpages.

javascript ajax tools


3-Growl 2.0 with Mootools Growl is a notification system for Mac OS X, it allows applications that support Growl to send you notifications.

javascript ajax tools


APIs

4-Google AJAX Language API With the AJAX Language API, you can translate and detect the language of blocks of text within a webpage using only Javascript. The language API is designed to be simple and easy to use to translate and detect languages on the fly when offline translations are not available.


5-Got API An easy to use interface that helps you reach the methods and functions of many JavaScript frameworks by getting the data from trusted sources and websites.

javascript ajax tools


6-WaveMaker Visual Ajax Studio WaveMaker’s Studio and Framework provides a powerful solution for rapidly developing web-based applications. Drag & drop assembly of widgets and service, code-free integration of web-services, databases and Ajax UI, and one-touch deployment to standard Tomcat servers all work seamlessly together to let you build complete web apps in hours!

javascript ajax tools


FrameWorks

7- SproutCoreSproutCore is a framework for building applications in JavaScript with remarkably little amounts of code. It can help you build full ā€œthickā€ client applications in the web browser that can create and modify data, often completely independent of your web server, communicating with your server via Ajax only when they need to save or load data.

javascript ajax tools


8-JavaScriptMVCJavaScriptMVC is a framework that brings methods to the madness of JavaScript development. It guides you to successfully completed projects by promoting best practices, maintainability, and convention over configuration.

javascript ajax tools


Amazing Tools

9-Jaxer Jaxer is an Ajax server. HTML, JavaScript, and CSS are native to Jaxer, as are XMLHttpRequests, JSON, DOM scripting, etc. And as a server it offers access to databases, files, and networking, as well as logging, process management, scalability, security, integration APIs, and extensibility.

javascript ajax tools


10-The Regulator The Regulator is an advanced, free regular expressions testing and learning tool that allows you to build and verify a regular expression against any text input, file or web, and displays matching, splitting or replacement results within an easy to understand, hierarchical tree.

javascript ajax tools


11-SnippelySnippely is a basic text and code organizational tool. Instead of storing bits of code, quick notes, and memos in text files all over your hard drive, this application will let you save and organize ā€œsnippetsā€ in one convenient location.

javascript ajax tools


12-NitobiBugIt’s a browser-based JavaScript object logger and inspection tool - similar to Firebug. NitobiBug runs across different browsers (IE6+, Safari, Opera, Firefox) to provide a consistent and powerful tool for developing rich Ajax applications. You can check a demo here.

javascript ajax tools


13- Google Mashup EditorThe Google Mashup Editor provides simple tools and features that allow you to create mashups in minutes with the following features:

  • A set of tags that compiles into AJAX UI components.
  • Syntax highlighting
  • Autocomplete of gm tags by pressing the tab button
  • Quick access to documentation for any tag by pressing F2
  • File upload and management
  • Error checking and notification

javascript ajax tools


14- Beautify JavascriptThis tool was intended to explore ugly javascripts, e.g compacted in one line, or just make scripts look more readable.


15- ThemeRollerThemeRoller allows you to design custom jQuery UI themes for tight integration in your projects.

javascript ajax tools


16- JSDocJSDoc is a tool that parses inline documentation in JavaScript source files, and produces an documentation of the JavaScript code.


17- Clean AJAX Clean is an open source engine for AJAX, that provides a high level interface to work with the AJAX technology. It was created to solve real problems found on AJAX applications, and is used in many projects. Clean will help you to adopt AJAX saving your time and your code, reducing your learning curve and the code reengineering.

javascript ajax tools


18- Sajax Sajax is an open source tool to make programming websites using the Ajax framework as easy as possible. Sajax makes it easy to call PHP, Perl or Python functions from your webpages via JavaScript without performing a browser refresh. The toolkit does 99% of the work for you so you have no excuse to not use it.

javascript ajax tools


19- JavaScript Code Improver With JavaScript Code Improver you are just one click away from making any JavaScript clear, easily comprehensible and ready for printing thus saving the time you spend on editing, debugging and modifying it.

javascript ajax tools


Browser Addons and Toolbars

20- Greasemonkey Greasemonkey is a Firefox extension that allows you to customize the way web pages look and function. You can use it to make a web site more readable or more usable. You can fix rendering bugs that the site owner can’t be bothered to fix themselves.


21- Web Developer extension for Firefox This tool is really excellent for quick and easy webdevelopment. It Adds a menu and a toolbar with various web developer tools.

javascript ajax tools


22-Internet Explorer Developer Toolbar The Microsoft Internet Explorer Developer Toolbar provides a variety of tools for quickly creating, understanding, and troubleshooting Web pages.


23-DebugBar An Internet Explorer plug-in that brings you new powerful features :

  • DOM Inspector: View DOM Tree and modify tags attributes and css attributes on the fly to test your page
  • HTTP Inspector: View HTTP/S request to check cookies, GET and POST parameters, view server info
  • Javascript Inspector and Javascript Console: View javascript functions for easier debugging, see Javascript and AJAX code
  • HTML Validator: Validate HTML code to correct and optimize your code and html size of your page
  • And many more features: See page cookies, get pixel color on a page, make a page screenshot.

javascript ajax tools


24-Firebug Firebug integrates with Firefox to put a wealth of web development tools at your fingertips while you browse. You can edit, debug, and monitor CSS, HTML, and JavaScript live in any web page. It can be downloaded from here.

javascript ajax tools

8 Great CSS Frameworks

Jun 26, 2008 Author: Ashish | Filed under: Frameworks, HTML

Well, I guess I’m going to work backwords. There are three layers to the frontend; behaviour, presentation and markup. We’ve done behavior so we’re onto presentational now. CSS Frameworks have been all the buzz lately, we’ve had ones that use python ways of code then regenerate it as css, ones that are specifically for forms and an awesome one which is just for styling print!

Personally I find frameworks to much hassle, I have my own little framework but that is only really 20 or so lines. I might share it with all of you in the coming weeks if you would like it. Now here they are!

1. 960 Grid System - The 960 Grid System is an effort to streamline web development workflow by providing commonly used dimensions, based on a width of 960 pixels. There are two variants: 12 and 16 columns, which can be used separately or in tandem.

2. Blueprint CSS - Blueprint is a CSS framework, which aims to cut down on your CSS development time. It gives you a solid CSS foundation to build your project on top of, with an easy-to-use grid, sensible typography, and even a stylesheet for printing.

3. Hartija - The owner of Hartija describes it as a ā€œuniversal Cascading Style Sheets for web printingā€. It’s extremely customizable and very user friendly.

4. Formy CSS - Formy is mini CSS Framework for building web forms.

5. Clever CSS - CleverCSS is a small markup language for CSS inspired by Python that can be used to build a style sheet in a clean and structured way. In many ways it’s cleaner and more powerful than CSS2 is.

6. SenCSS - SenCSS is a sensible standards CSS Framework. This means that SenCSS tries to supply standard styling for all repetitive parts of your CSS, allowing you to focus on the fun parts. In that sense, senCSS is a bit like a large CSS Reset.

7. Elements -

Elements is a down to earth CSS framework. It was built to help designers write CSS faster and more efficient. Elements goes beyond being just a framework, it’s its own project workflow.It has everything you need to complete your project, which makes you and your clients happy. Read the Overview for more information.

8. LogicCSS - The Logic CSS framework is a collection of CSS files and PHP utilities to cut development times for web-standards compliant xHTML layouts.

This is just the tip of the iceberg, there are tones more css frameworks out there. I plan on releasing one for this site.

Friendly URLs in PHP: why do you care?

Jun 24, 2008 Author: Ashish | Filed under: PHP

Nice URLs, readable URLs, search-engine-friendly URLs. Different names same deal.

It can’t really be disagreed on that something like example.com/index.php?page=article&id=409 is not nearly as nice as example.com/article/409.

Turns out this isn’t all that hard with PHP - infact it can turn into something that’s very useful from more than just a readability viewpoint.

The Plan

What we’re going to do is capture everything past a particular point in our URL and pipe it to PHP, we’re going to let PHP do most of the the legwork.

* Using mod_rewrite we get everything past a particular point.
* We will then pass that into a PHP get variable. We’ll use ā€œpā€, you can use anything.
* In our PHP we will define ā€œrulesā€ for our URLs with very simple regular expressions.
* When something matches, we’ll get the appropriate page - otherwise we’ll give back a 404.

mod_rewrite

Yep, this article is purely from an Apache perspective, so I assume that you not only have Apache on your webserver, that you also have enabled mod_rewrite.

If you haven’t enabled mod_rewirite, it’s usually something like this in your http.conf:

LoadModule rewrite_module modules/mod_rewrite.so

Remember to restart Apache afterwards.

.htaccess

Let’s get .htaccess out of the way now. These are special files that you may, or may not have come accross. Basically, Apache will read these set of definable rules and determines what to serve when you visit a page.

In this case we’re going to use mod_rewrite rules. So, first create a file called .htaccess and open it up. (To Windows folk - It really has no ā€œfilenameā€, this might confuse some of the poorer text editors.)

To start with, we’re going to check if mod_rewrite is enabled - if it isn’t then Apache will return an internal server error (500).

All our rules will go inside this block.

First we need to enable the rewrite engine and set our base.

RewriteEngine on
RewriteBase /

The RewriteBase will tell Apache exactly where our capturing needs to come from, what the relative path is.

In our case we’re assuming we’re rewriting the root of a URL. If your script resided in a sub-directory like http://example.com/test, RewriteBase would have to be written like so:

RewriteBase /test

Our first rule will tell Apache where to go when we haven’t specified anything, in this case we simply want to go to index.php:

RewriteEngine on
RewriteBase /
 
# Nothing - Go to index.php
RewriteRule ^$          index.php  [L]

RewriteRule is how we define our actual rules.

Rewrite rules use regular expressions (regex for short), a kind of special text processing language, to define the rules. They can become very useful if you learn them properly, and we shall be using them later when we write the PHP portion of this article. PHP comes with reasonably good regex support built in.

In this case our regular expression is ^$. The caret symbol, ^, means ā€œAt the startā€. The dollar sign, $, means ā€œAt the end.ā€ So this pattern effectively matches nothing, there is nothing between the two symbols.

Don’t worry if regular expressions are confusing at first, there are many tutorials on it around.

The second part of RewriteRule defines where our rule goes to, in this case we always want an empty path to go to index.php.

The last part in square brackets defines a special flag, here we use the L flag. L defines this rule as the ā€œlast oneā€ - if this rule matches then Apache will disregard any further ones.

Our next rule is the one that we came here for:

RewriteEngine on
RewriteBase /
 
# Nothing - Go to index.php
RewriteRule ^$          index.php       [L]
 
# If anything matches, send the path to index.php
RewriteRule (.*)        index.php?p=$1  [L]

In regex a fullstop means ā€œany single characterā€ and asterisk means ā€œone or more of the previous characterā€. So our pattern is effectively - any amount of any character or simply, everything.

The parentheses around the rule indicate we want to group that match, and use it later. We do use in defining where our pattern goes to. You refer to groups with the dollar sign and the number of group. (Groups start at 1.) Again we will define this as the last rule with [L].

So with these two rules http://example.com will invisibly redirect to index.php and http://example.com/page/409 will rewrite to index.php?p=page/409.

Unfortunatly, if you try to go directly to any other file or directory, it will not show up - Instead the path will get sent to index.php! We can use RewriteCond to add additional conditions to rectify this situation.

RewriteEngine on
RewriteBase /
 
# Nothing - Go to index.php
RewriteRule ^$          index.php        [L]
 
# Condition - requested path is not a file or directory.
RewriteCond %{REQUEST_FILENAME}         !-f
RewriteCond %{REQUEST_FILENAME}         !-d
 
# If anything matches, send the path to index.php
RewriteRule (.*)        index.php?p=$1  [L]

In a little bit of slightly backward behaviour, when Apache finds a rewrite rule it will go back to see if there were any conditions and check those before finally matching. So these conditions must appear before the rule.

The first parameter is what we test against, it refers to a special server variable, in this case REQUEST_FILENAME. The second parameter is our actual condition. -f asks ā€œIs an existing fileā€ and -d is directories.

Since we only want to continue if the match is not a file we can use a !, so our final patterns are !-f and !-d.

Our rewrite ruleset is nearly complete, but there’s one tiny thing, sometimes you may want to pass GET parameters around in the URL the same way you normally would, as it stands these will be ignored by Apache when rewriting. We can use a flag to append all extra request parameters to the URL - QSA.

Our final .htaccess file looks like this:

RewriteEngine on
RewriteBase /
 
# Nothing - Go to index.php
RewriteRule ^$          index.php       [L]
 
# Condition - requested path is not a file or directory.
RewriteCond %{REQUEST_FILENAME}         !-f
RewriteCond %{REQUEST_FILENAME}         !-d
 
# If anything matches, send the path to index.php
RewriteRule (.*)        index.php?p=$1  [QSA,L]

If anything about mod_rewrite is confusing it’s worth knowing that the documentation on it is actually not all that terrifying and can help you understand it much better.

Using PHP to get the requested URL

Our rewrite rule will pipe everything into index.php as a GET parameter called ā€œpā€. So everything in our script will need to be included through this.

To start our index.php file we need to define a list of matches.

/*
 * Work out what page we are on
 */
$page_rules = array(
  "index" => "home.php",
  "about" => "about.php"
);
 
$page_val = (isset($_GET['p'])) ? $_GET['p'] : "index";

$page_rules is an associative array pointing matched rules to special pages. You can keep your eventually pages whereever you like, for our example we’ll simply have a ā€œpages/ā€ subdirectory where these will go in.

We set $page_val to our ā€œpā€ parameter if it was set, otherwise defaulting to index.

Next we go through all our rules and find if we’ve matched one with our parameter.

/*
 * Work out what page we are on
 */
$page_rules = array(
  "index" => "home.php",
  "about" => "about.php"
);
 
$page_val = (isset($_GET['p'])) ? $_GET['p'] : "index";
 
/*
 * Iterate through rules and test them on our request
 */
$match = NULL;
 
foreach($pages as $regex => $page_to)
{
 
  if(preg_match("/^".$regex."$/i", $page_val))
  {
    $match = $page_to;
    break;
  }
 
}
 
/*
 * If we didn't match anything deliver a 404 or include our file
 */
if($match === NULL)
  die("404");
else
  require "pages/".$page_to;

We now use preg_match to match against each of our rules.

For our index rule, the regular expression looks like /^index$/i. The forward slashes indicate the start and end delimeters of the regex, we can use extra flags to define special things, in this case we use the i flag which indicates that the match is case insensitive.

When we match a rule, we save the page name, then serve it later, or give a 404 message if not. (Your 404 message should be a lot better - this is a simple example after all.)

At this point our rewriting will work perfectly fine. There’s a few issues to work out first.
Small issues

First off, if you go to http://example.com/about the rule works, but if you go to http://example.com/about/ then nothing matches - our p variable has changed with that one character!
Luckily we can expand our regular expression to account for this. Question mark, ?, means ā€œthe previous character none or more timesā€. So /? would mean ā€œforward slash or no forward slashā€, except that as we know, forward slash means something in regular expressions. To escape characters in regex simply use the backslash character. The correct match is \/?.
Our new rule check looks like this:

if(preg_match("/^".$regex."\/?$/i", $page_val))
{
$match = $page_to;
break;
}

You may be starting to think that regular expressions can start to look messy the more complicated they get - you’d be right, but that doesn’t discount how useful they can be. A regular expression can be broken down into smaller parts if necessary.
This leads on to our second problem, if any of our matches have a forward slash in, which they most likely will, you will get an error when hitting the regex because it would be unescaped. A quick str_replace will sort that.

$regex = str_replace("/", "\/", $regex);
 
if(preg_match("/^".$regex."\/?$/i", $page_val))
{
$match = $page_to;
break;
}

Grouping
This is all well and good, but if you have a URL like our initial example of http://example.com/article/409 surely you’d have to make a new rule for each ID? Luckily we can leverage the power of regex to do that for us.
First we need to ammend our rules to match /article/ and any number. This is done like so:

$page_rules = array(
  "index"          => "home.php",
  "about"          => "about.php"
  "article/[0-9]+" => "article.php"
);

[0-9] is a range, a single number from 0 to 9. And whereas ? means ā€œzero or more timesā€, in this case we need to use plus, + which means ā€œone or more timesā€œ. So we’re now matching any integer.
Great, our rule works! But it’s useless to us if we can’t get that parameter out. Well, first we need to define this as a group in our regex by using parentheses, the same way we did in our .htaccess rules before.

$page_rules = array(
  "index"            => "home.php",
  "about"            => "about.php"
  "article/([0-9]+)" => "article.php"
);

To get our groups out of our regular expression we need to use the third parameter of preg_match, in which we pass in an array that will then be filled with our groups.
Our foreach loop needs to look something like this:

$match = NULL;
$matches = array();
 
foreach($pages as $regex => $page_to)
{
 
$regex = str_replace("/", "\/", $regex);
 
if(preg_match("/^".$regex."\/?$/i", $page_val, $matches))
{
$match = $page_to;
break;
}
 
}

Great, now if you tried to go to /article/409 and did a print_r of $matches, you’d get something like:
Array

(

[0] => article/43/

[1] => 43

)
The first entry is filled with the entire pattern, the second one is our requested ID - the group we defined in our match.
Notice that because we’ve defined any number, if you try to enter anything other than a number into the URL as an ID you will get given a 404 - This can act as a kind of first-defense validation for input variables.
This is almost the end of the article, however we can make this a little nicer to work with.
Named groups
Being able to refer to something like $_GET[’id’] is a convenience, there’s a name. $matches[1] is not so easy to dechyper - or even keep track of, what if we add another group that appears before it like a category name - the group number may shift.
Luckily with regex we can name our groups using the simple syntax of ? inside the start of the group. Our new rules can now look like this.

$page_rules = array(
  "index"                 => "home.php",
  "about"                 => "about.php"
  "article/(?<id>[0-9]+)" => "article.php"
);

Now when you print_r $matches you get:
Array

(

[0] => article/43/

[id] => 43

[1] => 43

)
You can still refer to the group as $matches[1], but we’re also given the option of $matches[’id’].
Conclusion

Our final PHP script looks like this:

/*
* Work out what page we are on
*/
$page_rules = array(
"index"                 =&gt; "home.php",
"about"                 =&gt; "about.php"
"article/(?[0-9]+)" =&gt; "article.php"
);
 
$page_val = (isset($_GET['p'])) ? $_GET['p'] : "index";
 
/*
* Iterate through rules and test them on our request
*/
$match = NULL;
$matches = array();
 
foreach($pages as $regex =&gt; $page_to)
{
 
$regex = str_replace("/", "\/", $regex);
 
if(preg_match("/^".$regex."\/?$/i", $page_val, $matches))
{
$match = $page_to;
break;
}
 
}
 
/*
* If we didn't match anything deliver a 404 or include our file
*/
if($match === NULL)
die("404");
else
require "pages/".$page_to;
 
?&gt;

We’ve implemented friendly URLs in a simple way that is also very easy to work with in your script, we even have some basic validation that wouldn’t get relying on $_GET.

Recent Comments