Share your knowledge and create a knowledgebase.
Now the day has come to celebrate the immediate availability of the long awaited 1.1 stable release of the symfony framework!
All these can add great improvements in your development efforts.
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.
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.
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.
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.
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.
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.
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.
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 /testOur 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" => "home.php", "about" => "about.php" "article/(?[0-9]+)" => "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 => $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; ?>
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.