Leaking Abstraction

Loosely coupled thoughts on web development

Archive for the ‘Tutorials’ Category

Part II: Managing CSS and JavaScript files within a Zend Framework App

leave a comment »

Since my first post seemed to garner a good amount of attention I thought I’d follow up with another post on how to optimize our CSS/JS view helper components a bit.

The biggest suggestion — and rightfully so, was to minify or gzip the extra controller/action Javascript or CSS file.
It doesn’t take a lot of imagination to implement an improvement. There are several easy ways we can prevent the client (our users) from needing to download another CSS or JS file to view a particular controller action.

Firstly, we can get both the CSS and JS files to output in-line instead of loading as a separate file very easily:

File: /application/views/helpers/JavascriptHelper.php

getRequest();
		$file_uri = 'media/js/' . $request->getControllerName() . '/' . $request->getActionName() . '.js';

		if (file_exists($file_uri)) {
			$this->view->headScript()->appendScript('/' . $file_uri);
		}
	}
}

In the CSS helper, we’ll use the HeadStyle helper instead of the HeadLink helper:

File: /application/views/helpers/CssHelper.php

getRequest();
		$file_uri = 'media/css/' . $request->getControllerName() . '/' . $request->getActionName() . '.css';

		if (file_exists($file_uri)) {
			$this->view->headStyle()->appendStyle(file_get_contents($file_uri));
		}

		return $this->view->headStyle();

	}
}

If you were using the previous version of the CSS helper, make sure you update your layout to echo the HeadStyle helper. Be aware that the file references (e.g., background images) in your controller / action CSS files will now have a new base URL, so you will need to update accordingly.

The next level – minifying the inline output

The next obvious step is to minify the additional output. My first inclination was to use the CSS/JS minify library aptly titled minify, however, that does a lot more than we need. I’m not a big fan of adding large libraries for the sake of one function, so let’s instead explore how we can create exactly what we need within our view helper.

A little more googling gets us to this solution. Sure, it’s not perfect, but performing 90% of the necessary packing is good for me.
My CSS view helper now turns into this:

File: /application/views/helpers/CssHelper.php

getRequest();
		$file_uri = 'media/css/' . $request->getControllerName() . '/' . $request->getActionName() . '.css';

		if (file_exists($file_uri)) {
			$css = $this->minify(file_get_contents($file_uri));

			$this->view->headStyle()->appendStyle($css);
		}
		return $this->view->headStyle();
	}

	function minify($css) {
		// 90% minifying from http://www.lateralcode.com/css-minifer/
		$css = preg_replace('#\s+#',' ',$css);
		$css = preg_replace('#/\*.*?\*/#s','',$css);
		$css = str_replace('; ',';',$css);
		$css = str_replace(': ',':',$css);
		$css = str_replace(' {','{',$css);
		$css = str_replace('{ ','{',$css);
		$css = str_replace(', ',',',$css);
		$css = str_replace('} ','}',$css);
		$css = str_replace(';}','}',$css);
		return trim($css);
	}

}

For the JS packer, we’ll use Dean Edward’s Javascript Packer that was ported to PHP by Nicolas Martin. You can download the class here:

Download Javascript Packer by Dean Edward

  •  

I added the JS packer to /library/jspacker/JavaScriptPacker.php. I modify my JavaScript helper by doing the following:

File: /application/views/helpers/JavascriptHelper.php

getRequest();
		$file_uri = 'media/js/' . $request->getControllerName() . '/' . $request->getActionName() . '.js';

		if (file_exists($file_uri)) {
			$javascript = file_get_contents($file_uri);
			require_once('jspacker/JavaScriptPacker.php');

			$packer = new JavaScriptPacker($javascript);
			$this->view->headScript()->appendScript($packer->pack());

			return $this->view->headScript();
		}
	}
}

The major disadvantage to this is debugging can be a pain when you don’t have line numbers or variable names to reference. Thus, I added a conditional statement that only packs the Javascript if not in the development environment:

$javascript = file_get_contents($file_uri);
if (APPLICATION_ENV != 'development') {
	$packer = new JavaScriptPacker($javascript);
	$javascript = $packer->pack();
}
$this->view->headScript()->appendScript($javascript);

Presto! Auto-minifying, auto-packing inline Javascript and CSS only when we need it for our controller/actions.

Next steps? I suspect our next step is to add some server side caching so all this parsing doesn’t happen in real time at the client’s expense. Look for a short part 3 using Zend_Cache very soon.

Questions, comments? Please feel free to leave them below!

Written by Andy Baird

February 15, 2010 at 1:22 am

Managing CSS and JavaScript files within a Zend Framework App

with 6 comments

When I’m creating a large external facing website or application, one of the biggest messes I used to end up making was in my CSS and JavaScript files.

As a developer/designer (jack of all trades, master of none, if you will) I tend to stay away from some of the more common developer solutions that take care of a lot of the design overhead (e.g., jQuery UI framework, Dojo, etc). Flexibility is paramount to good design — boxing yourself into a specific layout for every page is bound to produce a boring, forgettable website. Design is highly underrated to developers, I believe a good aesthetic sense is a skill worth maturing for anyone who develops web applications. After all, you can have the most beautiful underlying code, but if it’s presentation is anything short of beautiful it completely loses its “wow” factor.

Full design control usually means large, thousand plus line CSS files that equal serious pain when it comes to maintenance or building upon. If you don’t namespace your selectors carefully you’ll end up paying for it down the road. And heaven forbid you apply a default HTML tag styling. So, ranting aside, how do you maintain flexibility and still keep tidy CSS and JavaScript? My solution is to keep the very same directory/file structure that is used for the application for my CSS and JavaScript. The best part is by writing a very simple view helper, it’s super easy to automate the proper head link and script file inclusions.

Here’s what my CSS and JavaScript view helpers look like:

File: application/views/helpers/JavascriptHelper.php

getRequest();
		$file_uri = 'media/js/' . $request->getControllerName() . '/' . $request->getActionName() . '.js';

		if (file_exists($file_uri)) {
			$this->view->headScript()->appendFile('/' . $file_uri);
		}
	}
}

File: application/views/helpers/CssHelper.php

getRequest();
		$file_uri = 'media/css/' . $request->getControllerName() . '/' . $request->getActionName() . '.css';

		if (file_exists($file_uri)) {
			$this->view->headLink()->appendStylesheet('/' . $file_uri);
		}

		return $this->view->headLink();

	}
}

With that done, add the helper to your layout in the section:

File: application/layouts/scripts/layout.phtml


	
    <title>My app title</title>
    <?= $this->headTitle() ?>
    <?= $this->headMeta() ?>
    <? $this->headLink()->appendStylesheet('/media/css/global.css') ?>
    <?= $this->headLink()->appendStylesheet('/media/css/iefix.css','screen','lt IE 7') ?>
    <?= $this->cssHelper() ?>
    <?= $this->javascriptHelper() ?>

Now, anytime a controller action is invoked it will look for a javascript and css file in the same controller/action file path. In the above examples I’ve hard-coded the CSS and Javascript parent directories (/public/media for me) directly in to the code, but this would be pretty easy if you wanted to throw it in a config file or something instead. Otherwise just change to your preferred directory and your good to go.

The next thing I’d like to explore is automatically packing/minifying all CSS and Javascript into one file (or possibly outputting them directly to the layout in-line) and then caching the results of that to optimize bandwidth usage. If I ever have the luxury of that being a priority, that is :)

Written by Andy Baird

February 1, 2010 at 5:26 pm

Posted in Tutorials

Tagged with , ,

Running scripts in Zend Framework

leave a comment »

It’s always been a bit confusing to me where and how to execute scripts within my Zend Framework applications. Often times I would just initialize the autoloader and the classes myself in the script file itself.  Since the existence of Zend_Application, this has become a whole lot easier.

First, I create a folder called “scripts” in my application directory. This is an ideal location for scripts because it’s outside of the Apache HTTP root which means we don’t need to worry about remote execution. We can also easily point CRON jobs to this location instead of running some fangled CRON job to cURL a particular URL (Yes, I’m guilty of this, sadly).

Now, at the top of any script we write, add the following:

File: /application/scripts/anyscriptyouwrite.php
[ccew_php]
define(‘APPLICATION_ENV’,'script’);
require_once(‘../../httpdocs/index.php’);
[/ccew_php]

This sets our application environment to the “script” environment. Now, we will customize our Bootstrapper when running scripts by editing the index.php in the web root:

File: /public/index.php
[ccew_php]
if (APPLICATION_ENV == ‘script’) {
$application->bootstrap(‘Db’);
$application->bootstrap(‘Registry’);
/* ..etc.. */
} else {
$application->bootstrap()
->run();
}
[/ccew_php]

Notice, we don’t ever call the run() method, so the front controller never gets instantiated. This allows us to explicitly declare each resource we want to setup an environment more ideal for scripting.
Another cool side effect of using the APPLICATION_ENV is we can specify script-specific settings in our application.ini:

File: /application/configs/application.ini
[ccew_php]
[script : production ]
resources.db.adapter = PDO_MYSQL
resources.db.params.host = “hostname”
resources.db.params.username = “username”
resources.db.params.password = “password”
resources.db.params.dbname = “dbname”
[/ccew_php]

Written by Andy Baird

January 30, 2010 at 6:10 pm

Posted in Tutorials

Tagged with , ,

Zend_Db: query(), fetch methods, and Zend_Db_Select

leave a comment »

[cci_php]Zend_Db[/cci_php] provides several methods for querying a database. They range from a simple query wrapper to programmatically. Say we have database object [cci_php]$db = Zend_Db_Table::getDefaultAdapter()[/cci_php]:

query() – Will return the results of any SQL query.

fetchRow() – Will return only the first row of the result set.

fetchCol() – Will return only one column (the first one if your select statement will be used) as an array.

fetchOne() – Will return only the value of the first column of the first row of the query.

These methods return row objects wherever possible (for query(), fetchRow(), and fetchCol()). You can change this to an array by setting the fetch mode before executing the SQL:

[ccew_php]
$db->setFetchMode(Zend_Db::FETCH_ARRAY);
[/ccew_php]

Or, if you just want to get your results as an array in the first place, you can use [ccei_php]$db->fetchAssoc($query)[/ccei_php].

Creating queries programmatically with Zend_Db_Select

A [ccei_php]Zend_Db_Select[/ccei_php] statement produces SQL that is correct based on the adapter you are using. It also takes care of things you probably don’t ever bother to do when you write your own queries, such as deliberately expressing all tables along with their columns and properly escaping all table and column names. [ccei_php]Zend_Db_Select[/ccei_php] ultimately returns this query, so usage is simple:

[ccew_php]
$db->fetchRow($db->select()->from(‘sample’));
[/ccew_php]

In this case, [ccei_php]$db->select()->from(‘sample’)[/ccei_php] returns the following string:

[ccew_sql]
SELECT `sample`.* FROM `sample`
[/ccew_sql]

We can add parameters to our select statement easily:

[ccew_php]
$select = $db->select()->from(‘sample’);
$select->where(‘id=100′);
$select->order(‘id DESC’);
[/ccew_php]

Which produces:

[ccew_sql]
SELECT `sample`.* FROM `sample` WHERE (id=100) ORDER BY `id` DESC
[/ccew_sql]

With a little more research, you will quickly discover that you can perform nearly any non-complex query with [ccei_php]Zend_Db_Select[/ccei_php].

When to use Zend_Db_Select and writing SQL directly

The first thing you probably took away from Zend_Db_Select (at least I did) is the fact that it makes writing really simple queries way more complicated than they should be.

And, well, you’re right. It’s hard to fight the instinct that using Zend_Db_Select feels like the right thing to do – it feels like it’s the convention that a good programmer is supposed to follow. The reality is, for your application, you probably don’t need to use it. Here’s the list of conditions I came up with where I use Zend_Db_Select over writing the query directly.

  • You are writing an application that needs to run on top of different types of RDBMS?
  • You are writing a piece of code that you want to use in several different applications where the environments are unknown.
  • You are writing a query that will be modified based on different logic conditions.

For the average application, you probably won’t find yourself needing Zend_Db_Select that much. That said, when you do need it, nothing can beat it for the level of abstraction it provides.

Written by Andy Baird

January 9, 2010 at 1:36 am

Posted in Tutorials

Tagged with ,

Using Zend_Db standalone

leave a comment »

If there is one class I had to pick out of the ZF library as the crown jewel, it would without a doubt be Zend_Db.
I rarely touch a PHP application or script that interacts with any database without utilizing this class.

Let’s go over the quick list of why it’s my fave:

  • It automatically wraps PDO extensions and normalizes them as best as possible across different types of databases (in simple terms: change from a MySQL database to an MS SQL or PostgreSQL database with minimal code change)
  • It sanitizes data input for you automatically (as long as you use it correctly)
  • You can quickly grab results in array or object form without performing any post query operations.
  • Provides methods for programatically creating queries

On top of that, it’s easily decoupled from the rest of the library. Let’s start out by ripping out Zend/Db.php and the Zend/Db folder and dropping it in our app.

Initializing the database connection

Now, in our settings / boilerplate file let’s initialize the database adapter. The database adapter uses a lazy connection (meaning it doesn’t actually connect to the database until you perform a query with it) by default. This makes the application settings a perfect place to setup our database object.

[ccew_php tab_size="4"]
$db = Zend_Db::factory('Pdo_Mysql', array(
	'host'             => 'localhost',
	'username'         => 'database_username',
	'password'         => 'database_password',
	'dbname'           => 'database'
));
[/ccew_php]

That’s easy enough. If the application is simple and you plan on referencing the $db variable every time you want to make a query, you can stop right there. If you plan on using the database connection within a function or class scope, you don’t have to re-initialize it every time (or use icky global variables). Zend_Db_Table comes with a static function for setting the default database adapter.

[ccew_php]
require_once('Zend/Db/Table.php');
Zend_Db_Table::setDefaultAdapter($db);
[/ccew_php]

And now within our classes or functions, we can easily call it at any time:

[ccew_php]
class MyClass {
	private $db;
	function __construct() {
		$db = Zend_Db_Table::getDefaultAdapter();
	}
}
[/ccew_php]

Presto. Persistent database object any time we need it in our application / script.

Written by Andy Baird

January 5, 2010 at 4:01 pm

Posted in Tutorials

Tagged with ,

Follow

Get every new post delivered to your Inbox.