php, webdev

ZendCon 2010 – Caching on the Edge

PHP Caching on the Edge

The goal is to never generate the same response twice.
This is another ‘notes post’ – nothing too organize here (for now).

Changing the HTTP headers with php:
header(‘Content-Type: text/plain’);

Caching  spec – read it on the night you feel like you can’t sleep.

1. HTTP expiration

Is the data fresh? only when the version is stale we will go to the server to get a new data.
HTTP Headers for Expiration

2. HTTP validation

Last-Modified / If-Modified-Since
ETag / If-None-Match

(!) Http cache headers only work with ‘safe’ HTTP methods (GET/HEAD) – meaning, these method won’t change the application state.

Expires – give the date/time after which the response is considered stale.
$expires – gmdate(‘D, j M Y H:i:s T’, time()+5); // expire in 5sec
header(‘Expires: ‘ . $expires);

* With expiration of less then few days you might hit problems because the clock in the web server and the clock in the client is not showing the same time.
* HTTP/1.1 spec says that you are not allowed to send expire for more then 1 year in the future. WHY?

A better way:
* Use cache-control
header (‘Cache-Control: max-age=5’);

(!) So use expire only for things you want to cache for very long time (more then 48h).
On other cases, use cache-control.

Usage of ETag

You can compute the etag on your own or use a tool that do the work for you (some good framework).
ex: http://http.trainings.sensiolabs.com/etag.php

* Expiration wins over Validation – first we checking the expiration.
* Expiration allows you to scale as less requests hit your server.
Validation saves bandwidth.

PHP and cache

http://http.trainings.sensiolabs.com/cookie.php

session_start();
$_SESSION['foo'] = 'bla';

(!) By default – when you set a cookie… php set for YOU no-cache/no-store/must-revalidate
Because if you have a cookie, you don’t want to cache the page.
It’s more a ‘safe’ default. So no one else could take this information from you.

header(‘Cache-Control: private/public, max-age=5’);
private – will prevent any proxy from cache this page.

Types of Caches

1. Browser cache – for example it’s good for images.

2. Proxy cache – inside a company/organization. It still on the ‘client side’ and it will mask all the clients that site behind it.
We can find it in big companies and lots of ISPs. It’s public.

3. Gateway cache (=reverse proxy or Http Accelerator or Surrogate Cache) – This is just like a proxy BUT it is on the server side.
Shared cache on the server side. Make your site more scalable, reliable and improve performance.

Gateway cache

In practice, most caches avoid anything with: cache-control, cookie, www-authenticate, post/Put, 302/307 status codes.
Cache-Control in php save us with a safe default of ‘private’.

A gateway cache won’t cache anything ‘private’ or carrying a cookie – so how can we use Google Analytic and still have cache?
use varnish… or any other proxy that remove+add the cookies before the request hit the server.

In cases where you want your code to run with reverse proxy like Akamai/varnish (esi tag is supported) you should use:

Surrogate-Capability: abc=”Surrogate/1.0 ESI/1.0″
Surrogate-Control: content =”ESI/1.0″ <– this will let the reverse proxy to parse the tags.

(!) You need to set these features in Varnish (they are not there by default).

Symfony2 – got a reverse proxy that is written in PHP. You might want to use it if you can’t afford to use varnish (it’s free – but let say your hosting company won’t install it)

In the end of the day, you want to hit the application as less as possible.
You can do it with HTTP headers and ESI.

Last but not least, please remember that, the one who picks his targets carefully, acts quietly, and achieves his objectives — he wins wars.

Standard
JavaScript

ZendCon 2010 – JavaScript for (real) beginners

Warning: this is not a real post…
It is more ‘some notes’ I’ve took in one of the morning sessions in ZendCon 2010

—
* In php associative array are very powerful – in Java script the keys will be integer.
You can have the same ‘associative’ if you build your own object that contain the features.

var obj1 = new Object();
obj1['foo'] = 'momo';
obj1.foo2 = 'bobo';

var obj2 = {
‘foo’ : ‘bar’,
‘confObj’ : ‘bla-bla’
}
console.log(obj1);
console.log(obj2);

* Nice way to use array {key1: “value”};
* The ‘this‘ keyword – what it point to now? A good question with more then one answer.
* ‘new‘ – create a copy from the function/obj and assign it.
* instanceOf – are X is instance from Y? (return as string)
* typeOf – lots of return options.

*

functions

both as objects and as contractor or procedural

as Procedural


function ff(str) {
console.log('ff is:' + str);
}

as an Object


var foo2 = function(str){
this.str = str;
this.say = function(){
console.log('inside say let see what is str:'+str);
}
this.say();
}

prototype – a way to let you inheritance
* jQuery (Mr. Rasig) show a nice way to do a way of ‘class’ / obj and standard inheritance.
For example:

var Robot = function(name){
this.name = name;
this.say = function(){
console.log("bla bla my name " + this.name );
}
}
myRob = new Robot("momo");
// refine say
myRob.say = function() {
console.log("Yo - my name " + this.name );
}

// lets add to the ‘class’ definition a new function – it will be in all the obj. we created from it
Robot.prototype.showDown() = function(str) {
console.log (‘bye bye ‘ + str);
}

Useful sites/resource to keep learning the core of JS (and not just some ‘cool’ animation):
** eloquentjavascript.net
** mozilla – core and ref
* nczonline.net
* wtfjs.com

Books:
* JavaScript: The Definitive Guide – David Flanagan
* JavaScript: The Good parts – Doulas crockford
* JavaScript Patterns – Stoyan Steganov
* High-Performance JavaScript – Nicholas C. Zakas

On twitter you can find more #zc10 or #zendcon

Standard
Business, webdev

How To Build Your Next Mobile App? (Cleverly)

Why the current app stores are broken? Well, Apple was the first to recognize that the real our of their wonderful hardware (=iPhone) and great software (=iOS and all its components) is outside the company. It’s in the developers (how is counting them now?) that build amazing eco system on top of their app store. It’s not only ‘Angrey Bird’ but huge amount of apps (Netflix, Evernote, Pandora, Twitter, Facebook etc’) that give you a device that can do so much more then ‘just’ mobile phone.

Quite late, lots of other big forces join the party:

  • Chrome OS & Mozilla App Store with their HTML5 concept. You can see more and more HTML5 apps that give you the look & feel of a native app. The ability to have: local storage, drag&drop, audio, video etc’ in your hands is great.
    280 North was the first company that put it as a mission to bring the web app to a level of desktop (=native) apps. Their cappuccino framework is showing the power of javascript with modern browsers and real strong web developers behind it.
    Well, their projects show that the gap is closing fast. Moreover, you can see today, web apps like Gmail that give you more and more. Even on the mobile web-kit.
  • Android (Yes – the ‘java’ the Oracle is now taking them to court on) – it’s very similar to Objective C of Apple.
    The concept is that you get great tools to build apps.
    The main problem is that you need to be locked (just like in the iPhone world) to Android with your code.
  • Palm (Now HP) with phoneGap and the ability to ‘write once’ deploy anywhere. PhoneGap is an open source development framework for building cross-platform mobile apps. Build apps in HTML and JavaScript and still take advantage of core features in iPhone/iPod touch, iPad, Google Android, Palm, Symbian and Blackberry SDKs. Their goal is to give web developers (that know JS, CSS and HTML) the tools to ‘transform’ their apps to be native on different platforms. I haven’t play with it (yet) – but I’ll do it soon.

Here is a good explanation from Mozilla lab (=Pascal Finette) on why the current app stores are broken:

Enjoy and keep building mobile apps. One main point to keep in mind is the size that today seems to be all belong to Apple. I guess that in the near future, when will see Google iPads with Chrome OS, things will be different. Any way, it should be a world where like: Pandora apps, your apps are working every where: laptop, iPad, iPhone, Mobile, TV etc’

Standard
webdev

Bootstrap File Example For Zend Framework

Here is some good starting file I’ve been using.
Please let me know if you think it’s good/bad/ugly/great:

<?php
/**
* Bootstrap file for zend framework
* @category zend framework tutorials
* @author Ido Green
* @see http://framework.zend.com
*/
error_reporting(E_ALL|E_STRICT);
ini_set(“display_errors”, “on”);

set_include_path(get_include_path(). PATH_SEPARATOR . ‘../library/’. PATH_SEPARATOR . ‘../application/models/’);
require_once “Zend/Loader.php”;

/**
* Required classes – if you use autoLoader you don’t need it… but it’s good to see what you might want to use.
*/
Zend_Loader::loadClass(‘Zend_Controller_Front’);
Zend_Loader::loadClass(‘Zend_Config_Ini’);
Zend_Loader::loadClass(‘Zend_View’);
Zend_Loader::loadClass(‘Zend_Session’);
Zend_Loader::loadClass(‘Zend_Log’);
Zend_Loader::loadClass(‘Zend_Controller_Request_Http’);
Zend_Loader::loadClass(‘Zend_Debug’);
Zend_Loader::loadClass(‘Zend_Auth’);
Zend_Loader::loadClass(‘Zend_Db’);
Zend_Loader::loadClass(‘Zend_Db_Table’);
Zend_Loader::loadClass(‘Zend_Registry’);

Zend_Session::start();

require_once “Zend/Session/Namespace.php”;
$consumer = new Zend_Session_Namespace(“consumer”);
Zend_Registry::set(‘consumer’, $consumer);

$config = new Zend_Config_Ini(“../application/config.ini”, “dev”); // have dev,qa,staging and prod for your own… life.

// setup database
$db = Zend_Db::factory($config->db->adapter, $config->db->config->toArray());
Zend_Registry::set(‘config’, $config);

Zend_Db_Table::setDefaultAdapter($db);
Zend_Registry::set(‘db’, $db);

require_once “Zend/Log/Writer/Stream.php”;
$writer = new Zend_Log_Writer_Stream(‘/tmp/our-project.log’);
$logger = new Zend_Log($writer);
Zend_Registry::set(‘logger’, $logger);

$front = Zend_Controller_Front::getInstance();
$front->setControllerDirectory(‘../application/controllers’);
$front->setParam(‘noViewRenderer’, true);

if($config->staging) {
$front->throwExceptions(true);
}
else {
$front->throwExceptions(false);
}

$front->dispatch();
?>

Standard
Business, JavaScript, webdev

Chrome Extentions – IMHO, Very Cool Technology

Last week we had our 2nd FedEx day here at High Gear Media HQ (yes – we like to think big like Google, Yahoo and Atlassian). So we gave our developers lots of good pitza (tradition is tradition!) and some choose to hack on a new iPad application that we are going to ship soon. Some others, choose to check out the new Chrome App Store (or in its current status – chrome extension).

It was an excellent 24h and I hope we will have the video soon on youTube.

Here is the first chrome extension that took me less then one hour! It’s very cool that Google choose to take all the skills that any web developer will have (HTML, CSS, JS) and build their concept around it. When you take the new goodies that HTML5 is giving you (check this html5rocks for all the amazing capabilities) and you think that this new app store will be the way to users to install applications on their chrome OS ‘iPads’ – you start to see the huge potential.

Here is the 2nd extension that let you set your own car and get news/recall alerts on it. Cool, no?

We have some more ideas and with local storage, Geo location and other great HTML5 features we will ship some more extensions to the table. Our new APIs let us build these applications very quickly. I hope that we will be able to open most of them to the public so others could build on top of them. For now, if you feel like hacking on the best automitive API that is out there… try:

Something like: http://feeds.highgearmedia.com/?tags=sport – to get all the ‘sport’ information that we produce. Or http://feeds.highgearmedia.com/?tags=prius if you own one.
Of course you can change the ‘prius’ with any make-model that you own and still get all the content for that. If you are into ‘Green’ and want to check what is the new progress with specific model you can use: http://feeds.highgearmedia.com/?tags=camry,green

All these will bring you feeds (ATOM) that you can consume easily. Enjoy.

What is FedEx day?

This is our version of Google 20% time to work on ‘cool/new’ stuff.

The Goal
We are coming to the office early on FedEx day and ship something over one day of work, hence Fedex Day – “We deliver”.

The Rules

  • From 8.30 to 9 we brainstorm everyone’s ideas of what could be done, and developers sign up for tasks.
    This can be around a ‘theme’ or a bigger idea/project we want to push.
  • Developers can either work alone or in pairs.
  • The development task must be something “out of the ordinary”. This is hard to define – but basically the spirit is that you can’t do something you would normally do. It’s a chance to attack all those “I wonder if XYZ would work… “, “It would be nice if we could… ” small development tasks that always get pushed off in the heat of battle.
  • The development task must be deliverable in one day. This doesn’t mean it has to be finished, polished and shipped (although it’s awesome if we can get there), but it can’t be an “open engine”. It must do something and work to some extent. It must show enough promise that we should continue working on it, or can it.
  • Pizzas/Drinks are ordered in, support is handled in advance and all other assigned tasks are obviated for the day so that developers have nothing to do but code.
  • At about 5.30, we’ll meet up for a “show off” meeting where developers get to show off what they’ve done, combined with chocolate cake and beer.
Standard
Business, webdev

New Data Stack Workshop: Building A Scalable Internet Datacenter

Here are few notes I took during yesterday conference in Stanford. The organizer (=Accel) did a very good job in bring some of the leading minds in the new emerging field of ‘Scalable’ and ‘Cloud’. Right… all of the speakers were ‘Accel companies’ – but they are the one who pushing the technology forward – so we cool with that.

The first company was NorthScale (and their chief architect is the same guy that we helped a year ago – with some real world data from high gear media servers). They have a very impressive open source project – Membase What is Membase you ask? Well, “Membase is an open-source (distributed, key-value database management system optimized for storing data behind interactive web applications. These applications must service many concurrent users; creating, storing, retrieving, aggregating, manipulating and presenting data in real-time. Supporting these requirements, membase processes data operations with quasi-deterministic low latency and high sustained throughput.”

In a nutshell:

  • Membase it’s like memcached but better.
  • Simple – get/set works with memcache client.
  • Fast – ram, ssd and disk layer.
  • Predictable latency.
  • Availability – All nodes are created equal.
  • Replication between data centers.

The second company was Cloudera – The bring to the table a full stack of Analytical Data Platform (ADP).

  • It’s not only a map/reduce solution but the full stack of ‘watching the wheels moving’ and understanding where you want to steer them.
  • BI is science for profit.
  • View of the world / answer question to make money
  • Pose hypothesis and validate them.
  • A/b testing – feeding the business with real world hypothesis and their verifications.
  • HDFS and map/reduce
  • Jim gray – ‘fourth paradigm’
  • HBase – base on google bigTable.
  • Hive – SQL intercede for Hadoop.
    What is Hadoop? Hadoop is the popular open-source implementation of MapReduce, a powerful tool designed for deep analysis and transformation of very large data sets
  • A good paper from Google: “The unreasonable effectiveness of Data’
  • Beautiful data – buy the book.

Last (for me) was Facebook. Here the story is very simple… scaling from 4-5M in 2006 up to 400M now is putting some challenges on the development team.

  • Scaling to 400M (efficiency is taking a hit at the beginning)
  • Need all the data all the time.
  • You / 100 friends / 100 objects-friends = 10’s of possible objects.
  • Web Server / memcached / MySQL – and make sure you can replicate boxes in each layer without any changes to your code.
  • Testing – Testing and some more unit testing, A/B Testing, System testing… you got the point.
  • Push a new version every week. Don’t let your software ‘get old and stick’.
  • Monitor EVERYTHING and when there is a problem always do what every you can in order to understand the root cause. Yes – even after you fixed it and everything is working now.
  • No single point of failure (sometimes – your software will be the single point of failure).

Overall, it was very productive 3h that will make us try few new opensource projects. Good times.

Standard
JavaScript, webdev

jQuery 101 – Quick Good Presention with Examples

I saw this one few days ago… very cool pretension that will give you the power of jQuery in less then 5min.

Like the best things out there. Their power is lay in a simple philosophy they are based on. In jQuery case:

1. Find some DOM elements. For example: $(“p”)

2. Do something with them. For example: $(“#myDiv”).html(“<h2>Yo yo – this is very impressive bike</h2>”);

The power is the simplicity and the way you can chain functions. Example: $(“#myDiv”).html(“foo bar!”).fadeIn(slow); <– yes, this will make the addition fading into the screen in a nice slow animation. Try to think how many lines of JavaScript you need for that. There are lots of other goodies in the pretension – so give it a ride.

Last but not least (for every developer, designer and well… human) – coffee. I know some will say Starbucks is NOT coffee. But nevertheless, this ‘poem’ on the cup got my attention. As we know, it’s not about YOU…

You and starbucks

Standard
JavaScript, life, webdev

Advanced jQuery & Javascript For Your Web App

This is an excellent 25min that (the one and only) John Resig gave at the Future of Web Apps conference in Miami 2010.
If you don’t know when to use the new features of jQuery 1.4.2 like: .live and .delegate events – you must see it.

Main points to take home with you:

  1. Event delegation –  Event delegation is a technique that routes around the traditional method of binding events. You must understand it and start using it if you have apps that use a lot of DOM elements. The example he gave was of a table with 10,000 cells. You do not need to bind the event to each cell but rather one event to the table element and by using the bubbling of events in the browser these events will be executed with less code and more efficiency.
  2. Use CDN. What is a CDN you ask? Well, A CDN is short for Content Delivery Network and what that effectively translates into is a bunch of geo-position data centers around the globe. Not all of us have the finances to build a whole bunch of data centers all around, but there are a number of great services that handle this. Amazon CloudFront is one that we (at High Gear Media) use and they are good and cheap.
  3. Minifying and gzipping your JavaScript. Easy and save lots of time. Performance – performance – performance (like Steve balamer like to say).
  4. Use jQuery UI and don’t re-invent the wheel. jQuery UI is a set of components and set of widgets that you can use, you can drop into your application, and they will just work. I’ve used them over and over again and each time they are getting better and better with a great API that let you (the developer) all the power to customize and work with them.
Standard
webdev

How To Deal With High Gear Media API Using PHP And XPath

For the serious players in the automotive industry on the net there is a new way to improve their sites. We had this feed for a while, but now with the new improvements and after big players (e.g. yahoo autos) have been happy with it, we wanted to share it with others around the world.
For developers that are not used to work with XML, XPath and other goodies, here is a short sample of code that will show you how easy it is to fetch our full feed. Unlike the previous post about our regular RSS feed, I’ve used here some basic functionality that anyone that used php (5.2+) will have under their belt.

<?php
/**
* @author Ido Green
*
* @since 04/10/2010
*
* @abstract Simple example how to fetch High Gear Media Full API using xPath
*
* @see greenido.wordpress.com
*
* @copyright HighGearMedia INC. 2010
*
*/error_reporting(E_ALL); // Always good to have it in development mode
$feed = new DOMDocument();
$feed->load('http://www.thecarconnection.com/api?uid=YourApiUserKey&cat=bottom-line');
if (isset($feed->documentElement)) {
$xpath = new DOMXPath($feed);
// Lets register TheCarConnection namespace
$xpath->registerNamespace('tcc', 'http://www.thecarconnection.com/rss');
// Now we looping on all the items and for each one we are extracting some data
foreach ($xpath->evaluate('//item') as $entryNode) {
// Simple way to get the title,desc per item
echo "Title: " . $xpath->evaluate('string(title)', $entryNode), "\n";
echo "Description " . $xpath->evaluate('string(description)', $entryNode), "\n";
// and some more interesting capabilities of xPath - we fetching the spec that is under tcc namespace for car details
echo "Make: " . $xpath->evaluate('string(tcc:review[1]/tcc:cardetails[1]/tcc:make[1])', $entryNode), "\n";
echo "Model: " . $xpath->evaluate('string(tcc:review[1]/tcc:cardetails[1]/tcc:make[1])', $entryNode), "\n";
echo "Rating: " . $xpath->evaluate('string(tcc:review[1]/tcc:cardetails[1]/tcc:rating[1])', $entryNode), " Out of 10\n";
echo "============\n";
}
} else {
echo 'Error: Could not fetch the feed';
}

 

You can also clone this code from github using: git clone git://gist.github.com/865542.git gist-865542

So it’s easy, right? You can load these feed for each site from our network.
For example: http://www.motorauthority.com/api?uid=YourUserKey&cat=reviews
Will give you all the reviews from Motor Authority.
For more specific custom calls you may use these parameters:

  • uid – your user ID
  • cat – you can choose: reviews / bottom-line / tips / blogs
    If you wish to get just the summaries of the bottom-line use: bottomline-summary
  • media – Use 0 for strip html and media=1 to have our HTML format in the call.
  • from/to – Use unix time stamp (e.g. 1206514800 and yes… the ‘from’ need to be lower then the ‘to‘)
  • limit – Up to 100 items. The default is 10.
  • limited-links – When it’s equal 1 we will give you just 5 links per item.
  • version – You will only need it if you wish to get reviews for cars that are older then 2008. Then use: version=0
  • morelinks – Use 1 if you wish to get links from thecarconnection.com or 0 if you don’t want links.

(*) Note that the bold parameters are mandatory.

If you wish to have quality automotive content on your site please feel free to approach High Gear Media
(feedback at HighGearMedia.com) and get a user ID. With more then 1000 new items of content per month, there are something for every car lover girl.

Standard
webdev

How To Work With High Gear Media RSS Feed In (less then) 4 Minutes


For all the girls that asked me time after time ‘How/Who/When/Why?’ and for all the ones that want to have on their blog the best automotive content around the web… This short code example will harness you with a knowledge to fetch High Gear Media customizable feed and have it on your site. The first thing you need to do in order to save yourself some leg work is to install Zend Framework.

Why reinvent the wheel, right?

The good people that work with Zend build for us some nice components that save us lots of work. For example, to parse an Atom (or RSS) feed – you should use their class and in few lines of code, you can be productive and happy.

After the installation, you can copy & paste the code below and you good to go.

<?php
/**
* @author Ido Green
*
* @since 04/01/2010
*
* @abstract Simple example how to fetch High Gear Media API (XML feed).
* You should have Zend Framework (1.9.4 and above).
*
* @see greenido.wordpress.com
*
* @copyright HighGearMedia INC. 2010
*
*/
// Set error reporting to ALL - Always good when you developing new features
error_reporting(E_ALL);
// Lets make sure we can find Zend Framework lib. (You might want to change it base on your local
// environment.
set_include_path(get_include_path() . PATH_SEPARATOR . "../");
// get the feed library
require_once 'Zend/Feed.php';
try {
$rss = Zend_Feed::import('http://feeds.highgearmedia.com/?sites=thecarconnection,greencarreports,allaboutprius');
} catch (Exception $e) {
echo $e->getMessage(); // In case something didn't work - lets see it.
exit (-1);
}
$feedItems = array();
// Loop through the items in the feed
foreach ($rss as $item) {
$itemElements = array(
'title' => $item->title(),
'description' => $item-<description(),
'link' => $item->link(),
'pubDate' => $item->pubDate(),
'author' => $item->author()
);
array_push($feedItems, $itemElements);
}
echo "\nThe HGM feed we got:\n";
// dump all items
var_dump($feedItems);
// In case some other process want to check if we finished correctly.
exit(0);
?>

The feeds can be fully customize according to your interested topics. For example:

Please feel free to share you experience using the comments.

Standard