Client side framework’s should be called client side libraries; here’s why:

library-booksThis isn’t a really important post, it’s just something I think need’s to be expressed and accepted; it must be accepted. Mootools, YUI, jQuery, Dojo etc. are great. They help a person with very tedious javascript techniques, speed up your applications, and make the UX much richer.

But they are not frameworks. I know this probably just seems like a semantics issue, but I want to make it clear that they are not frameworks, they are libraries. From http://dictionary.reference.com/browse/framework

frame⋅work  [freym-wurk] Show IPA
–noun
1. a skeletal structure designed to support or enclose something.
2. a frame or structure composed of parts fitted and joined together.
3. the construction or sale of frames.
4. work done in, on, or with a frame.

A framework should be referenced only when your development is surrounded or incased by some structure. On the php side of things, this makes sense; an MVC based framework since every piece of code you write it part of the execution of the framework. On the client side though, it’s not so clear cut.

While you can work inside of a client side library as if you were in a framework (eg. creating new, framework-specific, classes), most of the code you write is simply using the library to help it out. As an example, you attach event handlers, create and manage JSON, make ajax calls, etc. All of this you can do natively, or you can have the library help you out. But when you use one of the library’s helpers, you’re not tied to it. You’re still writing native javascript, just short-cutting through the library’s helper methods and naming conventions.

I’m not sure why this deserved a post, such a long post at that. I suppose as I learn more about true frameworks, I’m realizing that semantics like this really do matter. When I write in CI or Cake, I have to fall in line with their file, naming and folder conventions. I need to work inside of a controller, which is triggered by the framework. I need to define the interface in view/template/layout files, which are loaded and compiled by the framework. And I need to access the data set through their ORM, which is managed by the framework.

JavaScript isn’t like that.
Now while the specific cases I’m talking about (YUI,dojo,jQuery,Moo) are in my eyes libraries, that’s not to say that there couldn’t be/aren’t client side frameworks. I imagine javascript/ajax driven applications (large ones like gmail or a few Ycombinator/startup’s) have client side frameworks.

They have these systems in place where you have to work inside of them; the work is delineated among an MVC pattern, or some sort of separation of logic. I think that’d be really cool to check out, but because of the nature of javascript, I don’t think it’s as necessary as it is on the server side. Maybe I’m just saying that because I haven’t really been exposed to one, but client side JS is more modular and sparse than server side development, and for that reason having a library to help you tap into short cuts makes tons of sense.

My last point though, is that while I’ll always consider these javascript extensions libraries, I can definitely understand how some people would call them frameworks due to the way they use them. If you constantly are creating new framework-specific classes that follow standard programming practices (eg. hierarchy, casting, separation of logic), I think it’d be fair to see you’re using the library AS a framework. I’m cool with that. Lets just be clear about how the extension is used by the general public.

Progressive enhancement

lego_bricksI was in an interviewing not too long ago for a company with a terrible terrible idea, with easily the most terrible team leader I’ve ever had the misfortune of speaking with in a professional context, when someone in the interview asked me about ‘Progressive Enhancement’.

I didn’t know what the term meant, and when he explained it to me, it made logical sense; it’s something that I’ve been doing for years, but I just never knew the formal name of it.

In a nut shell, progressive enhancement is a way of developing and designing a web experience to be optimal for the viewer. It’s a very general term/description, but it’s because it can be used in many different areas. For example, CSS is intself a progressive enhancement technique. The reason I say that is that when Google indexes your site, they don’t see CSS, they don’t see much layout; they just see a bunch of text, code and tags that they give importance to.

However, imagine now your friend checked out that site; if they viewed it the way google does, they wouldn’t be able to use it much (the internet of the early 90’s was like this). CSS came along and was designed to lift/boost the visual experience of a visitor that wasn’t a robot, and that could understand visual context.

But that’s the most general case, two that I’ve been doing lately include CSS3 graceful degradation, and ajax based hash-requests (my own term that I just though of now). CSS3 degradation is what it sounds like. I throw in a bunch of CSS3 for browsers like IE8, Safari 4, FF 3.5, that makes the user interface spark and work better. For the others, they aren’t affected, so nothing bad happens.

This one is common place, and has been for a while, but something that’s really cool and super effective (something Digg should’ve done for their digg bar url fiasco, which I can safely say as a backseat-driver), is anchor link experience degradation (another term I’ve coined now, and is linked to that above). Basically, all these anchor’s have href values that point to another page/experience right? Well using some not so fancy javascript, you can override the default behavior for browser that support javascript (eg. not google bots), to change the experience.

So for example, I’ve got a link on my homepage that points to my profile link yadda right? Google bot is going to hit this, visit that page, index it, and keep on moving. A user would normally do the same, but using progressive enhancement, I can make the experience so much better. I can make it so that when they hit the link, I capture the event, prevent it from happening, and instead take the href value and make an ajax call to the same url. My server is configured to notice that this is an ajax call for the profile page, and returns the contents of that page (or view) in a json object. I then only replace the part of the page that would be different for the profile. This prevents a full browser resource re-load (Eg. headers, footers, assets etc., don’t get loaded/requested again).

Now this isn’t just the core of what Ajax is about; ajax is about enhancing the user experience to prevent unnecessary loads. This is about changing the entire experience, all-together, to make your site completely ajax driven, bookmark-able (via url’s like website.com/#/users/onassar/profile/), navigation-able (made that up) through the forward/back links, and faster. It takes a lot of work both on the server and client side, but changes the entire scope of your application/site. But because you’re using progressive enhancement, you’re keeping google happy with new links for it to index (not like flash), and making two versions of your site; an ajax one which is faster, and a regular synchronous one which can be used for old school browsers.

This technique has always been buried into everything I’ve done on the client side, and while I didn’t know the name (and to be honest, as long as you’re implementing it the name shouldn’t/doesn’t matter), it’s something I’d really push for wherever possible. This has a lot to do with some more abstract concepts such as REST-ful resources/requests, but at the heart of it, it’s about improving the user experience to the highest capacity, and degrading gracefully when it won’t work.

Regarding the digg fiasco; basically, a bunch of people complained originally that when digg changed all the anchor url’s to point to their digg bar which pushed out a link in a frame, that they were losing SEO juice. Now which google could get pissed by this, a fairly straight forward, progressive enhancement technique couldn’t been to write out links like this:
yadda
Google would visit, and move on through to the page, passing along the ‘yadda’ seo juice. But then adding in some nice client side JS (weird that I have to say that, since there are not server side js ports), I could prevent the default action of that anchor, and redirect the url to digg.com/[REL VALUE].

This would keep the juice flowing, and improve the experience by redirecting to the digg bar url. While I’m sure they thought of this (super smart dudes over there), and maybe they ran into a google/search engine blacklisting situation since they were in fact leading google to a different experience than is intended for the real visitor, I would’ve been curious to see how bad the upset would’ve been.

PHP Reflection class: a gem I found

Narcissistic EagleIn developing my own mash-up of a framework, drawing inspiration from a lot of different areas, I ran into an interesting hurdles.

Since my framework is MVC based, I ran into a problem whereby calling an action/method in a controller should only be fulfilled if the number of parameters passed in was valid. So for example, if I was dealing with a user’s model, and I wanted to return the email address for the user, I would normally access it via a url pattern such as: http://www.website.com/users/details/email/

On the server side, this would access the Users controller, the details method, and pass in a parameter with the value ‘email’. The method would then grab it from the db, and return it however it decided. The trick came in, however, as to validating the parameters that were passed to a controller’s action/method. So for example, http://www.website.com/users/details/email/oliver/ would pass the details method/action two parameters with values ‘email’, and ‘oliver’.

But my method/action only accepts one. So what should happen? Well ideally, a 404/error page should be pushed out, but how would PHP know that the parameter count doesn’t match? You have two options. One is very intrusive, and the other is best thing ever.

1) Intrusive: in every action, hard code something like:
if(func_num_args()>HARDCODED_NUMBER)
// redirect
This would mean every action/method would need to do this check to make sure the right number of param’s were sent in (this doesn’t even take into account the minimum number of req’d parameters; only the max allowed.

2) The best way ever: before making a call to controller’s action use the Reflection class.
This class allows you to check the parameter requirements of a call BEFORE you actually make it. So using php5’s Reflection class, you can check to see how many parameters are required at a minimum (excludes required praams’), how many are the max, and even more fun stuff. This allows you to centralize the error handling for controller calls to the dispatcher (my naming convention for the class/method that actually makes the calls to an action/method), keep your code very clean and clear.

I did some checking, and it seems using this class isn’t too expensive since this information is contained by php be default; it’s just that this extension contains the API for actually accessing it.

It’s a win-win situation as far as I’m concerned.

Dynamic Variables Assignment?

195144566_b1b4a84991_bIn JS, I ran into a problem where I needed to create a shortcut string, and then turn that string’s value into a reference to a different object.
So for example, I create a string called ‘oliver’ under the variable shortcut like so:
var shortcut = 'oliver';

Then I have a bunch of other code in my framework, and to access any of it, I would write something like:
FRAMEWORK.doSomething();

I wanted the framework’s name space to be preserved (so that I could easily upgrade/update it without affecting any code), but I wanted to be able to use my shortcut handle to access the framework, such that writing the following would work as well:
oliver.doSomething();

This led me to the use of eval to run a js command in js itself to get the assignment/reference working properly like so:
eval(shortcut+' = FRAMEWORK');

This worked really well and met exactly what I was trying to do, but I’m always hesitant to use eval. I’ve heard terrible things about it’s security and performance (although most ajax is based on this function). I’ll look into it and update the post if I find anything, but for the mean while, this has helped me do what I was trying to. It allows me to write really general client side framework code that can then be extended easily into a new namespace without any conflicts. Very powerful stuff.

When I search for it on google, it didn’t come up right away. My search terms (hopefully writing this in the post will help someone else) were: dynamic javascript variable assignment.

ps. The picture is supposed to represent a ’shortcut’. not the best fit I don’t mind saying.

Update: window[name] = reference is the winner. I don’t know why it escaped me before. This should prevent the use of eval and will allow you to dynamically create variables in the window scope.

Performance Logging: a technique that works better with ajax

Real-Life-LogThere are tons of optimization/performance logging tools out there. Most frameworks (cake, CI) have their own, and I’m a big fan of pQp, for no other reason that it’s clean and nice to look at.

For the most part, though, I’ve always relied on my own practices. Spitting out the number of db queries (inserts, selects, explains, etc.), memcached hits, apc hits, global variables hits, memory usage, etc. etc. is something I do often and monitor non-stop during development.

Most of the time in doing so, I’ll spit out a custom table that has these stats arranged. Nothing fancy, but very functional. An issue I ran into was how to monitor/gauge ajax performance. I couldn’t just spit it out at the end of the buffer since the ajax was normally json encoded.

Something I came up with (I’m sure others have done this, but haven’t found it) is to, globally, in my development/local environment, attach all these metrics to the response headers instead. Using php this is fairly easy (I believe just using the header function). Then I can do the same with ajax without affecting the view that is rendered/compiled.

The problem obviously comes with watching this data. I do this non-stop. Every page load almost, I’m checking those stats to see if some code I wrote dramatically affected the load time, db hits, or whatever else I’m measuring at the moment. I don’t want to have to open up Firebug or some http header interceptor every time I want to take a look.

This is where a quick mootools class comes in. In a nutshell, when the page loads and whenever an ajax call is performed, I create a new PerformanceMonitor object which checks the header of the html page or ajax call and then spits that out somewhere on the page. I can define a callback function so that I can handle that data however I’d like, but what this now does is offer a universal way to monitor a request regardless of how it was retrieved. This should work with JSONP as well, and realistically, loading any asset at all can have this PerformanceMonitor plugged in (after the asset is loaded) to check how the server handled it.

I’ll update this post when I’ve made the mootools class optimized for general usage, but for now, hopefully this approach gives someone an idea to performance monitoring for a more complicated web app that doesn’t rely on pure synchronous requests.

Framework: S^3 (aka S cubed): I’m calling it Smart Setting Selection

558px-Selection.svgIn working on a custom framework (that’s uniting a lot of the best of the existing ones, but keeping it lean and cutting out what I don’t need), I ran into a configuration roadblock which caused me to write some nifty code.

Basically, this framework has a bunch of settings/config files, and some of the files (ini format, using parse_ini_file) are seperated by the following keywords:
local,development,staging,production

Basically meaning, if I have a configuration setting that is supposed to mean something like ‘maxTimeout = 500′, I could, and in a real world application, would have that setting store different values based on which server the code base is being run on (eg. my local would be a lot higher, but the other ones like the production would be much lower for optimization purposes).

This lead me to write some nifty code that will parse all the ini files, and then when I want to retrieve something, it does a check for one of those 4 reserved words. So a real world example would be something like this:

An ini file is parsed and has the following format:

Array
(
[local] => Array
(
[name] => TEST
[cookies] => 1
)
[production] => Array
(
[name] => TEST
[cookies] => 1
)
)

When doing a call to the function and asking for the setting ‘name’, recursively as it moves it’s way down the settings array, it’ll look to see if it contains a keyword of local, production, etc., and if it does, automatically set the value to that array/value. This will be clearer once I OS the framework which won’t be for a while, but to understand it from a code perspective, check this out:


public static function getDetails() {
$details = self::$details;
foreach(func_get_args() as $argument) {
$details = $details[$argument];
if(array_key_exists(Request::getServerRole(),(array) $details))
$details = $details[Request::getServerRole()];
}
return $details;
}

This means that my server will automatically pull the right setting detail based on what server is doing the requesting. I just need to setup my ini files so that if a setting needs to be different based on which server is being loaded, it can be.

Mootools caveat #2: noCache in new Request() is your friend

mootools_logoReading the docs is really worth it’s weight in gold. Namely, noCache option/parameter for a new Request (aka. Ajax for mootools) object really does make all the difference in the world.

“noCache – (boolean; defaults to false) If true, appends a unique noCache value to the request to prevent caching. (IE has a bad habit of caching ajax request values. Including this script and setting the noCache value to true will prevent it from caching. The server should ignore the noCache value.)”

I was having a problem with ajax being ‘retrieved’ by IE, but not actually making a hit in my access log. I was baffled, and figured it was a caching issue, but confused since safari/FF were working fine.

For those of you out there, be aware of this. My specific problem was actually based on a call to something like:
http://www.website.com/controller/action/

Now I can make that exact url call and have it return a bunch of html; but for the framework I’m working in, adding a header of AC:true (short form for ‘Ajax Call’) will change the output (namely, to a JSON object instead of pure html). It seems IE was caching the request since the page had been requested without the header, and then returning it every time.

Damn you IE!!!!! I understand <link /> and <script /> and <img />’s being cached, but XHR’s? Come on. They’re based on actions (eg. click events, mouse overs, key combinations), not default behaviors of a page load (ordinarily).

Mootools caveat: event.target is not extended by $

mootools_logoThis took me wayt too long to discover:
When using event.target via mootools event handlers, I figured out, after way too much testing, that event.target is NOT extended via $, and therefore doesn’t have accessors like .get(’tag’) and default’s for the $ (dollar sign extension).

I wasn’t sure if this was note worthy of a post, but I reckon I’ll fill this up with enough keywords that it’ll hopefully show up in the SERP’s for mootools event trigger target source, etc.

We shall see.