Monday

Build A Web 2.0 Voting Widget With Flex


IThere are few things that people like to do more than give their opinion about a subject of interest to them – especially on the Web. This can be very useful for engaging your site’s visitors, measuring their interest in a topic, or just allowing them to express themselves. Web 2.0, and the advent of Rich Internet Applications (RIAs), allow for the installation of polling widgets on your web site, making it easier than ever to take the pulse of your community.

There are several different technologies you could use to build an interactive voting widget, but the end user needs to be considered carefully. For instance, you could use Ajax – but this approach can introduce issues with client-side compatibility. You could use Applets, but that’s not a popular choice at the moment – too many web surfers disable the Java VM in their browsers.
A very good option, on the other hand, is Flash. Practically everyone has it installed – who hasn’t come across a link to YouTube at some point and wanted to watch a video?
But what if you’re not across Flash? And isn’t Flash really an animator’s tool anyway? Well, as we’ll see, it’s easy for developers to build Flash applications using the Flex framework – freely available as open source from Adobe. In this article, the first of two on this complex subject, we’ll walk through the process of building a Flash widget for voting using the Flex framework.
Flex Basics
Before we go any further, we’ll pause for a minute to talk about the Flex and Flash applications and where they fit into the client landscape. Take a look at the following graphic.
Where Flash applications fit into the client landscape
This diagram demonstrates how a Web 2.0 web page interacts with a PHP web server. The web page uses one of several tools to communicate with the web server. It can use Javascript and Ajax to make a request of the server, then update the page with the new data. Or it can use a Flash application to provide functionality to the user. This Flash application can either take up the entire page, or it may be contained to a widget that takes up just a portion of it. Flex has been used very successfully in both scenarios.
Flex applications are made of roughly three parts: the MXML that defines the interface, the ActionScript code that contains the application logic, and resources such as images and audio. To draw an analogy with web technologies, the MXML and ActionScript would be HTML and JavaScript respectively.
Now you could download the SDK and program your application using a simple text editor, but there’s a better option – a really good IDE called Flex Builder 3, available free from Adobe as a 30-day trial.
The following diagram shows Flex Builder 3 and how its function fits into the life cycle of generating a Flash application SWF.
How Flex Builder works
Flex Builder manages the MXML, ActionScript, and resources as a project. It uses the Flex SDK compiler to continuously compile the project as you make changes. That temporary output SWF file is then launched in your default browser to do the testing.
Hopefully this provides some context for getting started with Flex. If you’d like a more detailed walk-through of this subject, I recommend you try this excellent tutorial on Flex for beginners.
Getting Flex Up and Running
The Flex Builder 3 installer comes with everything you need built in. It automatically installs the Flex SDK, as well as the Eclipse-based IDE and the AIR runtime (which is useful if you want to build a desktop application rather than a web app.
Once you have Flex Builder 3 installed on your machine, launch it and you should see something like this.
The starting point with Flex Builder 3
This is the empty Flex IDE. The next step is to create our first Flex project. Select Flex Project from the New menu and you should see this window.
Creating your first project
You can name your project whatever you like. I chose Voteview, since for the purposes of this article I’m only going to build an application that views the current vote totals. We’ll discover the interactive widget in the next article.

After you hit Finish to build the project, you should see the result pictured below.
The auto-generated application
Flex Builder 3 automatically creates an MXML application with the same name as the project. In this case, the “voteview” project has one source file, voteviewer.mxml.
At this point, you’re probably thinking, “I thought we were doing Flex, so what’s this MXML?” MXML is one of the two major technologies in a Flex application; it’s a tag-based language used to build user interfaces. The other is ActionScript 3, which is the programming language that we use to add interactivity to the interface.
To make sure that everything’s working okay, we’ll add just a single tag to the MXML file, as shown here:

  1.   

  2.   
  3.   
      
  4.   




  

The tag specifies that we want a control of type Label with the text of Hello World where the font size is 20px. This figure shows the result of launching it in Flex Builder.
Just checking to make sure everything works
If that works, you know that everything is installed correctly and you’re all set to start developing in Flex.
The next step is to put an XML file on a web server that will contain the current vote totals. This is the data that the Flex application will fetch and display.
You can format your XML any way you choose, but something along these lines is simple enough:

  1.   
  2.   What is the best Star Wars movie?
      
  3.   
      
  4.     
      
  5.     
      
  6.     
      
  7.   
      
  8.   
  

  What is the best Star Wars movie?  

    

      

This XML defines that there is one question with three options, where each option has a name and a count of votes.
Once this XML file is up on your server somewhere (in my case, the localhost Apache server on my Mac), we can add some more tags to the MXML and get this party started!
Here’s a simple Flex application that reads the data from the XML file and then displays the question in a Label control, and the current votes in a DataGrid control:

  1.   
  2.   
  3.   creationComplete="votes.send()">
      
  4.   
      
  5.   
      
  6.   
      
  7.     
      
  8.       
      
  9.       
      
  10.     
      
  11.   
      
  12.   
  


  creationComplete="votes.send()">  

    

    

    

      

        

        

      

    

There are two key elements involved in the code above. The first is the mx:HTTPService tag that defines where we will retrieve the data, and specifies an id for the data source. This service is invoked by the code attached to the creationComplete event on the Application tag.
The data display is handled automatically by Flex through the magic of the Flex event model. When the HTTService has successfully downloaded the XML, the lastResult variable on the service notifies the Label and the DataGrid that it has changed. Those controls then update themselves automatically to show the new values returned by the server.
Here’s the result of launching this in Flex Builder.
A grid presentation of the data
Well, it works okay, but it’s not very sexy in appearance, is it? I’m all about the sexy look, so I’m going to use Flex’s built-in charting service to display the votes in a pie chart instead of a DataGrid.
This updated code is shown below:

  1.   
  2.   
  3.   creationComplete="votes.send()">
      
  4.   
      
  5.   
      
  6.   
  7.     showAllDataTips="true"
      
  8.     dataProvider="{votes.lastResult.votes.options.option}">
      
  9.     
      
  10.       
      
  11.     
      
  12.   
      
  13.   
  


  creationComplete="votes.send()">  

    

    

  
    showAllDataTips="true"  

    dataProvider="{votes.lastResult.votes.options.option}">  

      

        

      

    

The only change here is that we replaced the DataGrid with a PieChart control. When we run this in Flex Builder, we’ll see the window shown here.
A pie chart that displays the data
Now, that’s certainly better. A picture is worth a thousand words, as they say. But could it be even cooler? As it turns out, it can; the Elixir data visualization components available from ILOG offers a set of amazing charting controls that you can use on a trial basis.

Once we’ve installed the ILOG Elixir controls on the machine, we can link them into the project by referencing the Elixir libraries. From there, we add a reference to the Elixir PieChart3D instead of to the original PieChart control.
This updated code is shown below:
  1.  
      
  2.   
  3.   creationComplete="votes.send()" xmlns:ilog="http://www.ilog.com/2007/ilog/flex"> 
      
  4.    
      
  5.    
      
  6.   
  7.     showAllDataTips="true" 
      
  8.     dataProvider="{votes.lastResult.votes.options.option}" elevationAngle="30"> 
      
  9.      
      
  10.        
      
  11.      
      
  12.    
      
  13.   
   


  creationComplete="votes.send()" xmlns:ilog="http://www.ilog.com/2007/ilog/flex">   

     

     

  
    showAllDataTips="true"   

    dataProvider="{votes.lastResult.votes.options.option}" elevationAngle="30">   

       

         

       

     

And when brought up in Flex Builder 3, it looks like this figure.
A cool 3D pie chart of the vote results using Elixir
Now we’re really cooking with gas! With Elixir we can change the rotation of the chart, the colors, the viewing angle, the lighting, and more. We can even do all that on the fly by responding to mouseclick events and changing the parameters on the chart using ActionScript. This functionality allows the voter to spin the chart around and view it from different angles.
This is about as far as I’m going to go with the interface in this article series. To finish up, I’ll demonstrate how to use a different data transport technology, AMF, instead of XML. AMF is easier to use, particularly when you’re both reading and writing data – more on this in the next instalment!
NOTE:
AMF and XML aren’t the only ways that Flex can access data. Your applications can read JSON, text, AMF, or go direct to binary data through sockets. In other words, wherever your data is and whatever the format, Flex applications can get to it.

Going to AMF
Let’s use the free AMFPHP package to build an AMF service on the web server. AMFPHP comes with a built-in service browser, which I’ll show you in a minute, plus a directory where you put your services. In this case, we’ll add a new service to a new “votes” directory called VoteService.
Here’s the PHP code for VoteService:
  1.   
  2. include_once(AMFPHP_BASE . "shared/util/MethodTable.php"); 
      
  3. class VoteService 
      

  4.   
  5.   function getVotes() 
      
  6.   { 
      
  7.     return array( 'topic' => 'What is the best Star Wars movie?', 
      
  8.         'votes' => array(  
      
  9.             array( 'name' => 'Episode IV', 'count' => 150 ), 
      
  10.             array( 'name' => 'Episode V', 'count' => 250 ), 
      
  11.             array( 'name' => 'Episode III', 'count' => 50 ) 
      
  12.           ) 
      
  13.         ); 
      
  14.   } 
      
  15. }  

include_once(AMFPHP_BASE . "shared/util/MethodTable.php");   

class VoteService   

{   

  function getVotes()   

  {   

    return array( 'topic' => 'What is the best Star Wars movie?',   

        'votes' => array(    

            array( 'name' => 'Episode IV', 'count' => 150 ),   

            array( 'name' => 'Episode V', 'count' => 250 ),   

            array( 'name' => 'Episode III', 'count' => 50 )   

          )   

        );   

  }   

}
For this example, we’re just going to return the same data as we’d have gained from the XML file on the server. That way, if the results look the same we know everything’s in order.
To test the service, navigate to the amfphp/browser directory in your browser. You should see something like this.
The AMF data service viewed in the AMFPHP browser
Next, click on the votes/VoteService and hit the Call button. This causes the AMF browser to invoke the service and display the results, as shown here.
The AMF browser showing the vote service result
We can see that the data is returned correctly as an ActionScript object that’s very easy to manipulate.
From here, we can change the HTTPService from the original PieChart application to a RemoteObject service. The RemoteObject class connects to the AMF endpoint and then defines a bunch of methods. You can see this in the updated source:
  1.  
      
  2.   
  3.   creationComplete="voteRO.getVotes.send()"> 
      
  4.   endpoint="http://localhost/amfphp/gateway.php" 
      
  5.   source="votes.VoteService" destination="votes.VoteService" 
      
  6.   showBusyCursor="true"> 
      
  7.  
      
  8.  
      
  9.    
      
  10.   
  11.     showAllDataTips="true" 
      
  12.     dataProvider="{voteRO.getVotes.lastResult.votes}"> 
      
  13. ... 
      
  14.    
      
  15.   
   


  creationComplete="voteRO.getVotes.send()">   


  endpoint="http://localhost/amfphp/gateway.php"   

  source="votes.VoteService" destination="votes.VoteService"   

  showBusyCursor="true">   

   

   

     

  
    showAllDataTips="true"   

    dataProvider="{voteRO.getVotes.lastResult.votes}">   

...   

     

Yes, that’s a lot more code than the HTTPService required to achieve the same outcome (don’t forget to download the code archive for this article). But using AMF instead of XML will make it a lot easier to perform both the vote collection and vote addition from the widget that we’ll create in the next article of this series.


There are few things that people like to do more than give their opinion about a subject of interest to them – especially on the Web. This can be very useful for engaging your site’s visitors, measuring their interest in a topic, or just allowing them to express themselves. Web 2.0, and the advent of Rich Internet Applications (RIAs), allow for the installation of polling widgets on your web site, making it easier than ever to take the pulse of your community.
There are several different technologies you could use to build an interactive voting widget, but the end user needs to be considered carefully. For instance, you could use Ajax – but this approach can introduce issues with client-side compatibility. You could use Applets, but that’s not a popular choice at the moment – too many web surfers disable the Java VM in their browsers.
A very good option, on the other hand, is Flash. Practically everyone has it installed – who hasn’t come across a link to YouTube at some point and wanted to watch a video?
But what if you’re not across Flash? And isn’t Flash really an animator’s tool anyway? Well, as we’ll see, it’s easy for developers to build Flash applications using the Flex framework – freely available as open source from Adobe. In this article, the first of two on this complex subject, we’ll walk through the process of building a Flash widget for voting using the Flex framework.
Flex Basics
Before we go any further, we’ll pause for a minute to talk about the Flex and Flash applications and where they fit into the client landscape. Take a look at the following graphic.
Where Flash applications fit into the client landscape
This diagram demonstrates how a Web 2.0 web page interacts with a PHP web server. The web page uses one of several tools to communicate with the web server. It can use Javascript and Ajax to make a request of the server, then update the page with the new data. Or it can use a Flash application to provide functionality to the user. This Flash application can either take up the entire page, or it may be contained to a widget that takes up just a portion of it. Flex has been used very successfully in both scenarios.
Flex applications are made of roughly three parts: the MXML that defines the interface, the ActionScript code that contains the application logic, and resources such as images and audio. To draw an analogy with web technologies, the MXML and ActionScript would be HTML and JavaScript respectively.
Now you could download the SDK and program your application using a simple text editor, but there’s a better option – a really good IDE called Flex Builder 3, available free from Adobe as a 30-day trial.
The following diagram shows Flex Builder 3 and how its function fits into the life cycle of generating a Flash application SWF.
How Flex Builder works
Flex Builder manages the MXML, ActionScript, and resources as a project. It uses the Flex SDK compiler to continuously compile the project as you make changes. That temporary output SWF file is then launched in your default browser to do the testing.
Hopefully this provides some context for getting started with Flex. If you’d like a more detailed walk-through of this subject, I recommend you try this excellent tutorial on Flex for beginners.
Getting Flex Up and Running
The Flex Builder 3 installer comes with everything you need built in. It automatically installs the Flex SDK, as well as the Eclipse-based IDE and the AIR runtime (which is useful if you want to build a desktop application rather than a web app.
Once you have Flex Builder 3 installed on your machine, launch it and you should see something like this.
The starting point with Flex Builder 3
This is the empty Flex IDE. The next step is to create our first Flex project. Select Flex Project from the New menu and you should see this window.
Creating your first project
You can name your project whatever you like. I chose Voteview, since for the purposes of this article I’m only going to build an application that views the current vote totals. We’ll discover the interactive widget in the next article.

After you hit Finish to build the project, you should see the result pictured below.
The auto-generated application
Flex Builder 3 automatically creates an MXML application with the same name as the project. In this case, the “voteview” project has one source file, voteviewer.mxml.
At this point, you’re probably thinking, “I thought we were doing Flex, so what’s this MXML?” MXML is one of the two major technologies in a Flex application; it’s a tag-based language used to build user interfaces. The other is ActionScript 3, which is the programming language that we use to add interactivity to the interface.
To make sure that everything’s working okay, we’ll add just a single tag to the MXML file, as shown here:

  1.   

  2.   
  3.   
      
  4.   




  

The tag specifies that we want a control of type Label with the text of Hello World where the font size is 20px. This figure shows the result of launching it in Flex Builder.
Just checking to make sure everything works
If that works, you know that everything is installed correctly and you’re all set to start developing in Flex.
The next step is to put an XML file on a web server that will contain the current vote totals. This is the data that the Flex application will fetch and display.
You can format your XML any way you choose, but something along these lines is simple enough:

  1.   
  2.   What is the best Star Wars movie?
      
  3.   
      
  4.     
      
  5.     
      
  6.     
      
  7.   
      
  8.   
  

  What is the best Star Wars movie?  

    

      

This XML defines that there is one question with three options, where each option has a name and a count of votes.
Once this XML file is up on your server somewhere (in my case, the localhost Apache server on my Mac), we can add some more tags to the MXML and get this party started!
Here’s a simple Flex application that reads the data from the XML file and then displays the question in a Label control, and the current votes in a DataGrid control:

  1.   
  2.   
  3.   creationComplete="votes.send()">
      
  4.   
      
  5.   
      
  6.   
      
  7.     
      
  8.       
      
  9.       
      
  10.     
      
  11.   
      
  12.   
  


  creationComplete="votes.send()">  

    

    

    

      

        

        

      

    

There are two key elements involved in the code above. The first is the mx:HTTPService tag that defines where we will retrieve the data, and specifies an id for the data source. This service is invoked by the code attached to the creationComplete event on the Application tag.
The data display is handled automatically by Flex through the magic of the Flex event model. When the HTTService has successfully downloaded the XML, the lastResult variable on the service notifies the Label and the DataGrid that it has changed. Those controls then update themselves automatically to show the new values returned by the server.
Here’s the result of launching this in Flex Builder.
A grid presentation of the data
Well, it works okay, but it’s not very sexy in appearance, is it? I’m all about the sexy look, so I’m going to use Flex’s built-in charting service to display the votes in a pie chart instead of a DataGrid.
This updated code is shown below:

  1.   
  2.   
  3.   creationComplete="votes.send()">
      
  4.   
      
  5.   
      
  6.   
  7.     showAllDataTips="true"
      
  8.     dataProvider="{votes.lastResult.votes.options.option}">
      
  9.     
      
  10.       
      
  11.     
      
  12.   
      
  13.   
  


  creationComplete="votes.send()">  

    

    

  
    showAllDataTips="true"  

    dataProvider="{votes.lastResult.votes.options.option}">  

      

        

      

    

The only change here is that we replaced the DataGrid with a PieChart control. When we run this in Flex Builder, we’ll see the window shown here.
A pie chart that displays the data
Now, that’s certainly better. A picture is worth a thousand words, as they say. But could it be even cooler? As it turns out, it can; the Elixir data visualization components available from ILOG offers a set of amazing charting controls that you can use on a trial basis.

Once we’ve installed the ILOG Elixir controls on the machine, we can link them into the project by referencing the Elixir libraries. From there, we add a reference to the Elixir PieChart3D instead of to the original PieChart control.
This updated code is shown below:
  1.  
      
  2.   
  3.   creationComplete="votes.send()" xmlns:ilog="http://www.ilog.com/2007/ilog/flex"> 
      
  4.    
      
  5.    
      
  6.   
  7.     showAllDataTips="true" 
      
  8.     dataProvider="{votes.lastResult.votes.options.option}" elevationAngle="30"> 
      
  9.      
      
  10.        
      
  11.      
      
  12.    
      
  13.   
   


  creationComplete="votes.send()" xmlns:ilog="http://www.ilog.com/2007/ilog/flex">   

     

     

  
    showAllDataTips="true"   

    dataProvider="{votes.lastResult.votes.options.option}" elevationAngle="30">   

       

         

       

     

And when brought up in Flex Builder 3, it looks like this figure.
A cool 3D pie chart of the vote results using Elixir
Now we’re really cooking with gas! With Elixir we can change the rotation of the chart, the colors, the viewing angle, the lighting, and more. We can even do all that on the fly by responding to mouseclick events and changing the parameters on the chart using ActionScript. This functionality allows the voter to spin the chart around and view it from different angles.
This is about as far as I’m going to go with the interface in this article series. To finish up, I’ll demonstrate how to use a different data transport technology, AMF, instead of XML. AMF is easier to use, particularly when you’re both reading and writing data – more on this in the next instalment!
NOTE:
AMF and XML aren’t the only ways that Flex can access data. Your applications can read JSON, text, AMF, or go direct to binary data through sockets. In other words, wherever your data is and whatever the format, Flex applications can get to it.

Going to AMF
Let’s use the free AMFPHP package to build an AMF service on the web server. AMFPHP comes with a built-in service browser, which I’ll show you in a minute, plus a directory where you put your services. In this case, we’ll add a new service to a new “votes” directory called VoteService.
Here’s the PHP code for VoteService:
  1.   
  2. include_once(AMFPHP_BASE . "shared/util/MethodTable.php"); 
      
  3. class VoteService 
      

  4.   
  5.   function getVotes() 
      
  6.   { 
      
  7.     return array( 'topic' => 'What is the best Star Wars movie?', 
      
  8.         'votes' => array(  
      
  9.             array( 'name' => 'Episode IV', 'count' => 150 ), 
      
  10.             array( 'name' => 'Episode V', 'count' => 250 ), 
      
  11.             array( 'name' => 'Episode III', 'count' => 50 ) 
      
  12.           ) 
      
  13.         ); 
      
  14.   } 
      
  15. }  

include_once(AMFPHP_BASE . "shared/util/MethodTable.php");   

class VoteService   

{   

  function getVotes()   

  {   

    return array( 'topic' => 'What is the best Star Wars movie?',   

        'votes' => array(    

            array( 'name' => 'Episode IV', 'count' => 150 ),   

            array( 'name' => 'Episode V', 'count' => 250 ),   

            array( 'name' => 'Episode III', 'count' => 50 )   

          )   

        );   

  }   

}
For this example, we’re just going to return the same data as we’d have gained from the XML file on the server. That way, if the results look the same we know everything’s in order.
To test the service, navigate to the amfphp/browser directory in your browser. You should see something like this.
The AMF data service viewed in the AMFPHP browser
Next, click on the votes/VoteService and hit the Call button. This causes the AMF browser to invoke the service and display the results, as shown here.
The AMF browser showing the vote service result
We can see that the data is returned correctly as an ActionScript object that’s very easy to manipulate.
From here, we can change the HTTPService from the original PieChart application to a RemoteObject service. The RemoteObject class connects to the AMF endpoint and then defines a bunch of methods. You can see this in the updated source:
  1.  
      
  2.   
  3.   creationComplete="voteRO.getVotes.send()"> 
      
  4.   endpoint="http://localhost/amfphp/gateway.php" 
      
  5.   source="votes.VoteService" destination="votes.VoteService" 
      
  6.   showBusyCursor="true"> 
      
  7.  
      
  8.  
      
  9.    
      
  10.   
  11.     showAllDataTips="true" 
      
  12.     dataProvider="{voteRO.getVotes.lastResult.votes}"> 
      
  13. ... 
      
  14.    
      
  15.   
   


  creationComplete="voteRO.getVotes.send()">   


  endpoint="http://localhost/amfphp/gateway.php"   

  source="votes.VoteService" destination="votes.VoteService"   

  showBusyCursor="true">   

   

   

     

  
    showAllDataTips="true"   

    dataProvider="{voteRO.getVotes.lastResult.votes}">   

...   

     



Written By:Jack Herrington
Jack Herrington is an engineer, author, and presenter who lives and works in the San Francisco Bay Area. He lives with his wife, daughter and two adopted dogs. When he's not writing software, books, or articles you can find him cycling, running, or in the pool training for triathlons. You can keep up with Jack's work and his writing at http://jackherrington.com.

Sunday

How To Optimize Websites


Google found that moving from a 10-result page loading in 0.4 seconds to a 30-result page loading in 0.9 seconds decreased traffic and ad revenues by 20% (Linden 2006). When the home page of Google Maps was reduced from 100KB to 70-80KB, traffic went up 10% in the first week, and an additional 25% in the following three weeks (Farber 2006).
Tests at Amazon revealed similar results: every 100 ms increase in load time of Amazon.com decreased sales by 1%. (Kohavi and Longbotham 2007).


It’s quite clear. Everyone hates slow websites. The question is, how can you make your WordPress website faster? Keep reading and I’ll show you how you can take proactive steps towards speeding up your site.

What Determines Website Page Speed?

The Yahoo! YSlow and Google Page Speed Mozilla Firefox plugins evaluate your site against the widely accepted rules of website performance. The problem is, they don’t tell you what to do with the information they provide.
So, I’ll break down the top performance recommendations and show you you can apply them to your website.
Let’s do it.
  1. Minimize the number of HTTP requests
  2. Optimize and correctly display images
  3. Minify HTML, CSS, and Javascript
  4. Use a Content Delivery Network
  5. Gzip and compress components
  6. Choose over @import
  7. Put stylesheets at the top
  8. Put scripts at the bottom
  9. Utilize browser caching
  10. Use CSS Sprites

1. Minimize the number of HTTP requests

Translation: Limit the number of files required to display your website
When someone visits your website, the corresponding files must be sent to that person’s browser. This includes CSS files, Javascript library references, and images.
As expected, every file you use to enhance your design detracts from its performance. Similary, WordPress plugins are notorious for injecting extraneous CSS code in the head of your site without giving you the option to manually add the required styles to your stylesheet.
The key takeaway is this: eliminate everything that’s unnecessary. If you’re using a plugin because you like, take a look at how it impacts your code. The extra page-load time may not be worth it.

2. Optimize and correctly display images

Translation: Make images as small as possible and don’t require the browser to resize them
Depending on the format, many images contain a ton of extraneous metadata that can drastically increase the size of the file. Many designers fail to compress their images before uploading them to the web, and the overall impact of this can be dramatic with image-intensive designs.
Another cardinal sin of inexperienced webmasters is to upload and serve an image far larger than what is required for the design. WordPress is an unfortunate enabler of this, as many novice website owners upload large images directly off of their digital cameras and utilize WordPress’s image resizing functionality to display a smaller version.
With free applications like Picnik and Image Optimizer at our disposal, there is simply no excuse not to resize and optimize! Visitors (and your server) will thank you.

3. Minify HTML, CSS, and Javascript

Translation: Remove all white space from code when possible before serving it to visitors
The spaces, tabs, and orderly structure used in code is to make it more human-readable. Servers and browsers don’t care about what the code looks like as long as it’s valid and executes without error. If you want your files to download faster, you can remove this whitespace before serving your code.
Since it would be impractical to remove white space from files that are constantly edited (unlike Javascript libraries like jQuery, which are almost always served minified), we’ll want to leverage a plugin like WP-Minify (good) or W3 Total Cache (best) to handle this at runtime without affecting the files we need to edit.
Whitespace is great for web design but in our code? Not so much.

4. Use a Content Delivery Network (CDN)

Translation: Use a CDN to lighten the load on your server and turbocharge its performance
A CDN is a high-performance network of servers across the globe that replicate the static assets of your website and serve them to visitors from the closest POP.
What?
I know, I know. The good news is that we don’t have to understand the mechanics behind Content Delivery Networks in order to understand their power: you have a team of servers distributing your static assets to visitors across the globe. I’ve written a post on making WordPress faster by integrating a CDN if you’re interested in further reading on the topic.
CDNs are among the most effective ways to absolutely turbocharge the speed of our sites. We can’t neglect the other areas of optimization in the process, so this should be treated as the crowning jewel atop your beautifully optimized website.

5. Gzip and compress components

Translation: Compress files at the server level before sending them to browsers
If you were instructed to hurl a piece of paper across the room as far as it can go, would you lightly crumple it or squeeze it with all your might? That’s right, you’d get your Hulk Smash on.
The sample principle applies here: we want to allow our webserver to compress our files before sending them to visitors. We can drop a few lines of code in our .htaccess file to accomplish this:
#Begin gzip and deflate

    AddOutputFilterByType DEFLATE text/html text/css application/x-javascript text/plain text/xml image/x-icon
This code might look a bit intimidating, but it’s actually pretty simple. We’re just checking to see if the Apache mod_deflate module exists and if so, electing to serve HTML, CSS, Javascript, plain text, and favicon files using gzip compression.
Note that this requires the Apache webserver and the mod_deflate module. To enable gzip compression with NGINX, ensure that the following lines exist inside of the appropriate directive:
server {
        gzip on;
        gzip_types text/html text/css application/x-javascript text/plain text/xml image/x-icon;
    }
Easy!

6. Choose over @import

Translation: Beware the suck of IE!
When including your stylesheets, always link to the files instead of using the @import reference. IE handles them differently by loading them as if the reference was at the bottom of the document. [sarcasm] Nice work, Microsoft! [/sarcasm]

7. Put stylesheets at the top

Translation: All interface-related stylesheet references should be included in the of your document
We never, ever, ever want to display unstyled content to visitors—not even for a split second. Files responsible for the appearance of our site should be loaded first so they can be applied to the HTML as it loads. Makes sense, right?
Nothing more to it.

8. Put scripts at the bottom

Translation: All functionality-related files can be loaded after our content is loaded
As we think through how to deliver our content to visitors as fast as possible and the subsequent steps that users will take, we will use the following priorities:
  1. Get content to visitors as fast as possible
  2. Don’t allow unstyled content to appear in the browser (put CSS in the )
  3. Load the files required for interaction (tabbed widgets, certain external API calls, etc.) last
The thinking behind this is simple: users aren’t going to interact with the content before they can see it!

9. Utilize browser caching

Urban Translation: Where the cache at?
Standard Translation: Don’t require browsers to pull down another copy of static files every time
With browser caching, we’re explicitly instructing browsers to hang onto particular files for a specified period of time. When the file is needed again, the browser is to pull from its local cache instead of requesting it from the server again.
Running a website without caching in place makes as much sense as driving to the store for a glass of water every time you’re thirsty. Not only is in impractical and short-sighted, it takes more work!
The ExpiresByType directive is used to tell browsers which files to cache and how long to hang onto them. The example below would tell our visitors’ browsers to hang onto HTML, CSS, Javascript, and images, and favicon for an hour (3600 seconds):

    ExpiresActive On
    ExpiresByType text/html M3600
    ExpiresByType text/css M3600
    ExpiresByType application/x-javascript M3600
    ExpiresByType image/bmp M3600
    ExpiresByType image/gif M3600
    ExpiresByType image/x-icon M3600
    ExpiresByType image/jpeg M3600
Again, the code above is for your .htaccess file on an Apache server. The corresponding settings in NGINX would look something like this:
location ~* \.(jpg|png|gif|jpeg|css|js)$ {
        expires 1h;
}
Boom.

10. Use CSS Sprites

Translation: Serve one highly optimized image for your design to minimize the performance impact
A CSS sprite is an an image comprised of other images used by your design as something of a map containing the coordinates of all the images. Some clever CSS is used to show the proper section of the sprite when your design is loaded.
There are fantastic articles on the topic available across the web that dive into the mechanics of CSS sprites and wonderful resources for creating them. SpriteMe is a utility that generates the sprite and code required to make it work. If you inspect the code for the nav menu on Pearsonified.com, you’ll see a great example of how to implement a CSS sprite.

Whew! Still reading?

If so, great! You’re well on your way to a much faster website. If you implement even a handful of the techniques outlined in this post, you will see an immediate and dramatic improvement in your site’s performance. It’s not important that we know how everything works from database calls to HTTP requests—I surely don’t—it’s important that we’re familiar enough with the concepts to work towards them on our sites.

Work smarter, not harder

You could spend a few months learning the ins and outs of web server architecture, how different browsers implement caching, and how to tie it all together…or you could simply install and configure the W3 Total Cache plugin by Frederick Townes (CTO of Mashable).
I can give no higher recommendation for a performance-related plugin than this one. The features could easily fill another post, but I’ll give you the important part: W3TC helps you thoroughly address 80% of the recommendations outlined in this post. There are other solid options for caching plugins, but W3TC stands head and shoulders above the rest.

sources curtsy: diythemes.com

Thursday

Differences between PHP4 and PHP5

Here's a quick overview of what has changed between PH4 and PHP5. PHP5 for the most part is backwards compatible with PHP4, but there are a couple key changes that might break your PHP4 script in a PHP5 environment. If you aren't already, I stronly suggest you start developing for PHP5. Many hosts these days offer a PHP5 environment, or a dual PHP4/PHP5 setup so you should be fine on that end. Using all of these new features is worth even a moderate amount of trouble you might go through finding a new host!

Note: Some of the features listed below are only in PHP5.2 and above.

Object ModelThe new OOP features in PHP5 is probably the one thing that everyone knows for sure about. Out of all the new features, these are the ones that are talked about most!

Passed by ReferenceThis is an important change. In PHP4, everything was passed by value, including objects. This has changed in PHP5 -- all objects are now passed by reference.

PHP Code:
$joe = new Person();$joe->sex 'male';
$betty $joe;$betty->sex 'female';

echo 
$joe->sex// Will be 'female'  
The above code fragment was common in PHP4. If you needed to duplicate an object, you simply copied it by assigning it to another variable. But in PHP5 you must use the new clone keyword.

Note that this also means you can stop using the reference operator (&). It was common practice to pass your objects around using the & operator to get around the annoying pass-by-value functionality in PHP4.

Class Constants and Static Methods/Properties
You can now create class constants that act much the same was as define()'ed constants, but are contained within a class definition and accessed with the :: operator.

Static methods and properties are also available. When you declare a class member as static, then it makes that member accessible (through the :: operator) without an instance. (Note this means within methods, the $this variable is not available)

Visibility
Class methods and properties now have visibility. PHP has 3 levels of visibility:
  1. Public is the most visible, making methods accessible to everyone and properties readable and writable by everyone.
  2. Protected makes members accessible to the class itself and any subclasses as well as any parent classes.
  3. Private makes members only available to the class itself.
Unified Constructors and DestructorsPHP5 introduces a new unified constructor/destructor names. In PHP4, a constructor was simply a method that had the same name as the class itself. This caused some headaches since if you changed the name of the class, you would have to go through and change every occurrence of that name.

In PHP5, all constructors are named __construct(). That is, the word construct prefixed by two underscores. Other then this name change, a constructor works the same way.

Also, the newly added __destruct() (destruct prefixed by two underscores) allows you to write code that will be executed when the object is destroyed.

Abstract ClassesPHP5 lets you declare a class as abstract. An abstract class cannot itself be instantiated, it is purely used to define a model where other classes extend. You must declare a class abstract if it contains any abstract methods. Any methods marked as abstract must be defined within any classes that extend the class. Note that you can also include full method definitions within an abstract class along with any abstract methods.

InterfacesPHP5 introduces interfaces to help you design common APIs. An interface defines the methods a class must implement. Note that all the methods defined in an interface must be public. An interface is not designed as a blueprint for classes, but just a way to standardize a common API.

The one big advantage to using interfaces is that a class can implement any number of them. You can still only extend on parent class, but you can implement an unlimited number of interfaces.

Magic Methods
There are a number of "magic methods" that add an assortment to functionality to your classes. Note that PHP reserves the naming of methods prefixed with a double-underscore. Never name any of your methods with this naming scheme!

Some magic methods to take note of are __call, __get, __set and __toString. These are the ones I find most useful.

Finality
You can now use the final keyword to indicate that a method cannot be overridden by a child. You can also declare an entire class as final which prevents it from having any children at all.

The __autoload FunctionUsing a specially named function, __autoload (there's that double-underscore again!), you can automatically load object files when PHP encounters a class that hasn't been defined yet. Instead of large chunks of include's at the top of your scripts, you can define a simple autoload function to include them automatically.

PHP Code:
function __autoload($class_name) {
     require_once 
"./includes/classes/$class_name.inc.php";
}  
Note you can change the autoload function or even add multiple autoload functions using spl_autoload_register and related functions.

Standard PHP LibraryPHP now includes a bunch of functionality to solve common problems in the so-named SPL. There's a lot of cool stuff in there, check it out!

For example, we can finally create classes that can be accessed like arrays by implementing the ArrayAccess interface. If we implement the Iterator interface, we can even let our classes work in situations like the foreach construct.


Miscellaneous Features

Type Hinting
PHP5 introduces limited type hinting. This means you can enforce what kind of variables are passed to functions or class methods. The drawback is that (at this time), it will only work for classes or arrays -- so no other scalar types like integers or strings.

To add a type hint to a parameter, you specify the name of the class before the $. Beware that when you specify a class name, the type will be satisfied with all of its subclasses as well.

PHP Code:
function echo_user(User $user) {
    echo 
$user->getUsername();
}  
If the passed parameter is not User (or a subclass of User), then PHP will throw a fatal error.

ExceptionsPHP finally introduces exceptions! An exception is basically an error. By using an exception however, you gain more control the simple trigger_error notices we were stuck with before.

An exception is just an object. When an error occurs, you throw an exception. When an exception is thrown, the rest of the PHP code following will not be executed. When you are about to perform something "risky", surround your code with a tryblock. If an exception is thrown, then your following catch block is there to intercept the error and handle it accordingly. If there is no catch block, a fatal error occurs.

PHP Code:
try {
    
$cache->write();
} catch (
AccessDeniedException $e) {
    die(
'Could not write the cache, access denied.');
} catch (
Exception $e) {
   die(
'An unknown error occurred: ' $e->getMessage());
}  
E_STRICT Error Level
There is a new error level defined as E_STRICT (value 2048). It is not included in E_ALL, if you wish to use this new level you must specify it explicitly. E_STRICT will notify you when you use depreciated code. I suggest you enable this level so you can always stay on top of things.

Foreach Construct and By-Reference Value
The foreach construct now lets you define the 'value' as a reference instead of a copy. Though I would suggest against using this feature, as it can cause some problems if you aren't careful:

PHP Code:
foreach($array as $k => &$v) {
    
// Nice and easy, no working with $array[$k] anymore
    
$v htmlentities($v);
}
// But be careful, this will have an unexpected result because
// $v will still be a reference to the last element of the $array array
foreach($another_array as $k => $v) {

}  


New Functions

PHP5 introduces a slew of new functions. You can get a list of them from the PHP Manual.

New Extensions
PHP5 also introduces new default extensions.
  • SimpleXML for easy processing of XML data
  • DOM and XSL extensions are available for a much improved XML-consuming experience. A breath of fresh air after using DOMXML for PHP4!
  • PDO for working with databases. An excellent OO interface for interacting with your database.
  • Hash gives you access to a ton of hash functions if you need more then the usual md5 or sha1.
Compatibility IssuesThe PHP manual has a list of changes that will affect backwards compatibility. You should definately read through that page, but here is are three issues I have found particularly tiresome:
  • array_merge() will now give you warnings if any of the parameters are not arrays. In PHP4, you could get away with merging non-arrays with arrays (and the items would just be added if they were say, a string). Of course it was bad practice to do this to being with, but it can cause headaches if you don't know about it.
  • As discussed above, objects are now passed by references. If you want to copy a object, make sure to use the clonekeyword.
  • get_*() now return names as they were defined. If a class was called MyTestClass, then get_class() will return that -- case sensitive! In PHP4, they were always returned in lowercase.

ML self-service pipeline that abstracts Kubernetes complexity

  To successfully bridge the gap between machine learning engineering and cluster operations, you need to build a self-service pipeline that...