<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Leaking Abstraction &#187; Tutorials</title>
	<atom:link href="http://leakingabstraction.com/category/tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>http://leakingabstraction.com</link>
	<description>Loosely coupled thoughts on web development</description>
	<lastBuildDate>Wed, 20 Apr 2011 19:00:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='leakingabstraction.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Leaking Abstraction &#187; Tutorials</title>
		<link>http://leakingabstraction.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://leakingabstraction.com/osd.xml" title="Leaking Abstraction" />
	<atom:link rel='hub' href='http://leakingabstraction.com/?pushpress=hub'/>
		<item>
		<title>Part II: Managing CSS and JavaScript files within a Zend Framework App</title>
		<link>http://leakingabstraction.com/2010/02/15/part-ii-managing-css-and-javascript-files-within-a-zend-framework-app/</link>
		<comments>http://leakingabstraction.com/2010/02/15/part-ii-managing-css-and-javascript-files-within-a-zend-framework-app/#comments</comments>
		<pubDate>Mon, 15 Feb 2010 07:22:57 +0000</pubDate>
		<dc:creator>Andy Baird</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[minifier]]></category>
		<category><![CDATA[packer]]></category>
		<category><![CDATA[Zend_View_Helper]]></category>

		<guid isPermaLink="false">http://www.leakingabstraction.com/?p=141</guid>
		<description><![CDATA[Since my first post seemed to garner a good amount of attention I thought I&#8217;d follow up with another post on how to optimize our CSS/JS view helper components a bit. The biggest suggestion &#8212; and rightfully so, was to minify or gzip the extra controller/action Javascript or CSS file. It doesn&#8217;t take a lot [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leakingabstraction.com&amp;blog=15814748&amp;post=141&amp;subd=leakingabstraction&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Since my first post seemed to garner a good amount of attention I thought I&#8217;d follow up with another post on how to optimize our CSS/JS view helper components a bit.</p>
<p>The biggest suggestion &#8212; and rightfully so, was to minify or gzip the extra controller/action Javascript or CSS file.<br />
It doesn&#8217;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.</p>
<p>Firstly, we can get both the CSS and JS files to output in-line instead of loading as a separate file very easily:</p>
<p>File: <strong>/application/views/helpers/JavascriptHelper.php</strong><br />
<pre class="brush: plain;">
getRequest();
		$file_uri = 'media/js/' . $request-&gt;getControllerName() . '/' . $request-&gt;getActionName() . '.js';

		if (file_exists($file_uri)) {
			$this-&gt;view-&gt;headScript()-&gt;appendScript('/' . $file_uri);
		}
	}
}
</pre></p>
<p>In the CSS helper, we&#8217;ll use the HeadStyle helper instead of the HeadLink helper:</p>
<p>File: <strong>/application/views/helpers/CssHelper.php</strong><br />
<pre class="brush: plain;">
getRequest();
		$file_uri = 'media/css/' . $request-&gt;getControllerName() . '/' . $request-&gt;getActionName() . '.css';

		if (file_exists($file_uri)) {
			$this-&gt;view-&gt;headStyle()-&gt;appendStyle(file_get_contents($file_uri));
		}

		return $this-&gt;view-&gt;headStyle();

	}
}
</pre></p>
<p>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.</p>
<h1>The next level &#8211; minifying the inline output</h1>
<p>The next obvious step is to minify the additional output. My first inclination was to use the CSS/JS minify library aptly titled <a href="http://code.google.com/p/minify/">minify</a>, however, that does a lot more than we need. I&#8217;m not a big fan of adding large libraries for the sake of one function, so let&#8217;s instead explore how we can create exactly what we need within our view helper.</p>
<p>A little more googling gets us to <a href="http://www.lateralcode.com/css-minifer/">this solution</a>. Sure, it&#8217;s not perfect, but performing 90% of the necessary packing is good for me.<br />
My CSS view helper now turns into this:</p>
<p>File: <strong>/application/views/helpers/CssHelper.php</strong><br />
<pre class="brush: plain;">
getRequest();
		$file_uri = 'media/css/' . $request-&gt;getControllerName() . '/' . $request-&gt;getActionName() . '.css';

		if (file_exists($file_uri)) {
			$css = $this-&gt;minify(file_get_contents($file_uri));

			$this-&gt;view-&gt;headStyle()-&gt;appendStyle($css);
		}
		return $this-&gt;view-&gt;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);
	}

}
</pre></p>
<p>For the JS packer, we&#8217;ll use <a href="http://dean.edwards.name/">Dean Edward&#8217;s</a> Javascript Packer that was ported to PHP by Nicolas Martin. You can download the class here:</p>
<p><a class="download-link" href="http://www.zendframeworkhelp.com/files/JavaScriptPacker.zip">Download Javascript Packer by Dean Edward<span> </span></a></p>
<ul>
<li style="list-style-type:none;">&nbsp;</li>
</ul>
<p>I added the JS packer to <strong>/library/jspacker/JavaScriptPacker.php</strong>. I modify my JavaScript helper by doing the following:</p>
<p>File: <strong>/application/views/helpers/JavascriptHelper.php</strong><br />
<pre class="brush: plain;">
getRequest();
		$file_uri = 'media/js/' . $request-&gt;getControllerName() . '/' . $request-&gt;getActionName() . '.js';

		if (file_exists($file_uri)) {
			$javascript = file_get_contents($file_uri);
			require_once('jspacker/JavaScriptPacker.php');

			$packer = new JavaScriptPacker($javascript);
			$this-&gt;view-&gt;headScript()-&gt;appendScript($packer-&gt;pack());

			return $this-&gt;view-&gt;headScript();
		}
	}
}
</pre></p>
<p>The major disadvantage to this is debugging can be a pain when you don&#8217;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:</p>
<p><pre class="brush: plain;">
$javascript = file_get_contents($file_uri);
if (APPLICATION_ENV != 'development') {
	$packer = new JavaScriptPacker($javascript);
	$javascript = $packer-&gt;pack();
}
$this-&gt;view-&gt;headScript()-&gt;appendScript($javascript);
</pre></p>
<p>Presto! Auto-minifying, auto-packing inline Javascript and CSS only when we need it for our controller/actions.</p>
<p>Next steps? I suspect our next step is to add some server side caching so all this parsing doesn&#8217;t happen in real time at the client&#8217;s expense. Look for a short part 3 using Zend_Cache very soon.</p>
<p>Questions, comments? Please feel free to leave them below!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/leakingabstraction.wordpress.com/141/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/leakingabstraction.wordpress.com/141/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/leakingabstraction.wordpress.com/141/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/leakingabstraction.wordpress.com/141/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/leakingabstraction.wordpress.com/141/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/leakingabstraction.wordpress.com/141/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/leakingabstraction.wordpress.com/141/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/leakingabstraction.wordpress.com/141/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/leakingabstraction.wordpress.com/141/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/leakingabstraction.wordpress.com/141/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/leakingabstraction.wordpress.com/141/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/leakingabstraction.wordpress.com/141/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/leakingabstraction.wordpress.com/141/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/leakingabstraction.wordpress.com/141/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leakingabstraction.com&amp;blog=15814748&amp;post=141&amp;subd=leakingabstraction&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://leakingabstraction.com/2010/02/15/part-ii-managing-css-and-javascript-files-within-a-zend-framework-app/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/992221ea094450d55784b1f95dd27753?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">andybaird</media:title>
		</media:content>
	</item>
		<item>
		<title>Managing CSS and JavaScript files within a Zend Framework App</title>
		<link>http://leakingabstraction.com/2010/02/01/managing-css-and-javascript-files-within-a-zend-framework-app/</link>
		<comments>http://leakingabstraction.com/2010/02/01/managing-css-and-javascript-files-within-a-zend-framework-app/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 23:26:21 +0000</pubDate>
		<dc:creator>Andy Baird</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Zend_View_Helper]]></category>

		<guid isPermaLink="false">http://www.zendframeworkhelp.com/?p=115</guid>
		<description><![CDATA[When I&#8217;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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leakingabstraction.com&amp;blog=15814748&amp;post=115&amp;subd=leakingabstraction&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>When I&#8217;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.</p>
<p>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 &#8212; 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&#8217;s presentation is anything short of beautiful it completely loses its &#8220;wow&#8221; factor.</p>
<p>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&#8217;t namespace your selectors carefully you&#8217;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&#8217;s super easy to automate the proper head link and script file inclusions.</p>
<p>Here&#8217;s what my CSS and JavaScript view helpers look like:</p>
<p>File: <strong>application/views/helpers/JavascriptHelper.php</strong><br />
<pre class="brush: plain;">
getRequest();
		$file_uri = 'media/js/' . $request-&gt;getControllerName() . '/' . $request-&gt;getActionName() . '.js';

		if (file_exists($file_uri)) {
			$this-&gt;view-&gt;headScript()-&gt;appendFile('/' . $file_uri);
		}
	}
}
</pre></p>
<p>File: <strong>application/views/helpers/CssHelper.php</strong><br />
<pre class="brush: plain;">
getRequest();
		$file_uri = 'media/css/' . $request-&gt;getControllerName() . '/' . $request-&gt;getActionName() . '.css';

		if (file_exists($file_uri)) {
			$this-&gt;view-&gt;headLink()-&gt;appendStylesheet('/' . $file_uri);
		}

		return $this-&gt;view-&gt;headLink();

	}
}
</pre></p>
<p>With that done, add the helper to your layout in the  section:</p>
<p>File: <strong>application/layouts/scripts/layout.phtml</strong><br />
<pre class="brush: plain;">

	
    &lt;title&gt;My app title&lt;/title&gt;
    &lt;?= $this-&gt;headTitle() ?&gt;
    &lt;?= $this-&gt;headMeta() ?&gt;
    &lt;? $this-&gt;headLink()-&gt;appendStylesheet('/media/css/global.css') ?&gt;
    &lt;?= $this-&gt;headLink()-&gt;appendStylesheet('/media/css/iefix.css','screen','lt IE 7') ?&gt;
    &lt;?= $this-&gt;cssHelper() ?&gt;
    &lt;?= $this-&gt;javascriptHelper() ?&gt;

</pre></p>
<p>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&#8217;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.</p>
<p>The next thing I&#8217;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 <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/leakingabstraction.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/leakingabstraction.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/leakingabstraction.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/leakingabstraction.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/leakingabstraction.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/leakingabstraction.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/leakingabstraction.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/leakingabstraction.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/leakingabstraction.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/leakingabstraction.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/leakingabstraction.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/leakingabstraction.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/leakingabstraction.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/leakingabstraction.wordpress.com/115/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leakingabstraction.com&amp;blog=15814748&amp;post=115&amp;subd=leakingabstraction&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://leakingabstraction.com/2010/02/01/managing-css-and-javascript-files-within-a-zend-framework-app/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/992221ea094450d55784b1f95dd27753?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">andybaird</media:title>
		</media:content>
	</item>
		<item>
		<title>Running scripts in Zend Framework</title>
		<link>http://leakingabstraction.com/2010/01/30/running-scripts-in-zend-framework/</link>
		<comments>http://leakingabstraction.com/2010/01/30/running-scripts-in-zend-framework/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 00:10:39 +0000</pubDate>
		<dc:creator>Andy Baird</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[CRON]]></category>
		<category><![CDATA[scripts]]></category>
		<category><![CDATA[Zend_Application]]></category>

		<guid isPermaLink="false">http://www.zendframeworkhelp.com/?p=117</guid>
		<description><![CDATA[It&#8217;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 &#8220;scripts&#8221; [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leakingabstraction.com&amp;blog=15814748&amp;post=117&amp;subd=leakingabstraction&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>It&#8217;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.</p>
<p>First, I create a folder called &#8220;scripts&#8221; in my application directory. This is an ideal location for scripts because it&#8217;s outside of the Apache HTTP root which means we don&#8217;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&#8217;m guilty of this, sadly).</p>
<p>Now, at the top of any script we write, add the following:</p>
<p>File: <strong>/application/scripts/anyscriptyouwrite.php</strong><br />
[ccew_php]<br />
define(&#8216;APPLICATION_ENV&#8217;,'script&#8217;);<br />
require_once(&#8216;../../httpdocs/index.php&#8217;);<br />
[/ccew_php]</p>
<p>This sets our application environment to the &#8220;script&#8221; environment. Now, we will customize our Bootstrapper when running scripts by editing the index.php in the web root:</p>
<p>File: <strong>/public/index.php</strong><br />
[ccew_php]<br />
if (APPLICATION_ENV == &#8216;script&#8217;) {<br />
	$application-&gt;bootstrap(&#8216;Db&#8217;);<br />
	$application-&gt;bootstrap(&#8216;Registry&#8217;);<br />
	/* ..etc.. */<br />
} else {<br />
	$application-&gt;bootstrap()<br />
            -&gt;run();<br />
}<br />
[/ccew_php]</p>
<p>Notice, we don&#8217;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.<br />
Another cool side effect of using the APPLICATION_ENV is we can specify script-specific settings in our application.ini:</p>
<p>File: <strong>/application/configs/application.ini</strong><br />
[ccew_php]<br />
[script : production ]<br />
resources.db.adapter = PDO_MYSQL<br />
resources.db.params.host = &#8220;hostname&#8221;<br />
resources.db.params.username = &#8220;username&#8221;<br />
resources.db.params.password = &#8220;password&#8221;<br />
resources.db.params.dbname = &#8220;dbname&#8221;<br />
[/ccew_php]</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/leakingabstraction.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/leakingabstraction.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/leakingabstraction.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/leakingabstraction.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/leakingabstraction.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/leakingabstraction.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/leakingabstraction.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/leakingabstraction.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/leakingabstraction.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/leakingabstraction.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/leakingabstraction.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/leakingabstraction.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/leakingabstraction.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/leakingabstraction.wordpress.com/117/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leakingabstraction.com&amp;blog=15814748&amp;post=117&amp;subd=leakingabstraction&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://leakingabstraction.com/2010/01/30/running-scripts-in-zend-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/992221ea094450d55784b1f95dd27753?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">andybaird</media:title>
		</media:content>
	</item>
		<item>
		<title>Zend_Db: query(), fetch methods, and Zend_Db_Select</title>
		<link>http://leakingabstraction.com/2010/01/09/zend_db-query-fetch-methods-and-zend_db_select/</link>
		<comments>http://leakingabstraction.com/2010/01/09/zend_db-query-fetch-methods-and-zend_db_select/#comments</comments>
		<pubDate>Sat, 09 Jan 2010 07:36:32 +0000</pubDate>
		<dc:creator>Andy Baird</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Zend_Db]]></category>
		<category><![CDATA[Zend_Db_Select]]></category>

		<guid isPermaLink="false">http://www.zendframeworkhelp.com/?p=59</guid>
		<description><![CDATA[[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() &#8211; Will return the results of any SQL query. fetchRow() &#8211; Will return only the first row of the result set. fetchCol() &#8211; Will return only one column (the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leakingabstraction.com&amp;blog=15814748&amp;post=59&amp;subd=leakingabstraction&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>[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]:</p>
<p><img class="size-full wp-image-62 alignnone" style="vertical-align:text-top;" title="table-select-all" src="http://www.zendframeworkhelp.com/wp-content/uploads/2010/01/table-select-all.png" alt="" width="16" height="16" /> query() &#8211; Will return the results of any SQL query.</p>
<p><img class="size-full wp-image-65 alignnone" title="table-select-row" src="http://www.zendframeworkhelp.com/wp-content/uploads/2010/01/table-select-row.png" alt="" width="16" height="16" /> fetchRow() &#8211; Will return only the first row of the result set.</p>
<p><img class="size-full wp-image-64 alignnone" title="table-select-column" src="http://www.zendframeworkhelp.com/wp-content/uploads/2010/01/table-select-column.png" alt="" width="16" height="16" /> fetchCol() &#8211; Will return only one column (the first one if your select statement will be used) as an array.</p>
<p><img class="size-full wp-image-63 alignnone" title="table-select" src="http://www.zendframeworkhelp.com/wp-content/uploads/2010/01/table-select.png" alt="" width="16" height="16" /> fetchOne() &#8211; Will return only the value of the first column of the first row of the query.</p>
<p>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:</p>
<p>[ccew_php]<br />
$db-&gt;setFetchMode(Zend_Db::FETCH_ARRAY);<br />
[/ccew_php]</p>
<p>Or, if you just want to get your results as an array in the first place, you can use [ccei_php]$db-&gt;fetchAssoc($query)[/ccei_php].</p>
<h2>Creating queries programmatically with Zend_Db_Select</h2>
<p>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&#8217;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:</p>
<p>[ccew_php]<br />
$db-&gt;fetchRow($db-&gt;select()-&gt;from(&#8216;sample&#8217;));<br />
[/ccew_php]</p>
<p>In this case, [ccei_php]$db-&gt;select()-&gt;from(&#8216;sample&#8217;)[/ccei_php] returns the following string:</p>
<p>[ccew_sql]<br />
SELECT `sample`.* FROM `sample`<br />
[/ccew_sql]</p>
<p>We can add parameters to our select statement easily:</p>
<p>[ccew_php]<br />
$select = $db-&gt;select()-&gt;from(&#8216;sample&#8217;);<br />
$select-&gt;where(&#8216;id=100&#8242;);<br />
$select-&gt;order(&#8216;id DESC&#8217;);<br />
[/ccew_php]</p>
<p>Which produces:</p>
<p>[ccew_sql]<br />
SELECT `sample`.* FROM `sample` WHERE (id=100) ORDER BY `id` DESC<br />
[/ccew_sql]</p>
<p>With a little more <a href="http://framework.zend.com/manual/en/zend.db.select.html">research</a>, you will quickly discover that you can perform nearly any non-complex query with [ccei_php]Zend_Db_Select[/ccei_php].</p>
<h2>When to use Zend_Db_Select and writing SQL directly</h2>
<p>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.</p>
<p>And, well, you&#8217;re right. It&#8217;s hard to fight the instinct that using Zend_Db_Select feels like the right thing to do &#8211; it feels like it&#8217;s the convention that a good programmer is <strong>supposed </strong>to follow. The reality is, for your application, you probably don&#8217;t need to use it. Here&#8217;s the list of conditions I came up with where I use Zend_Db_Select over writing the query directly.</p>
<ul>
<li>You are writing an application that needs to run on top of different types of RDBMS?</li>
<li>You are writing a piece of code that you want to use in several different applications where the environments are unknown.</li>
<li>You are writing a query that will be modified based on different logic conditions.</li>
</ul>
<p>For the average application, you probably won&#8217;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.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/leakingabstraction.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/leakingabstraction.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/leakingabstraction.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/leakingabstraction.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/leakingabstraction.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/leakingabstraction.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/leakingabstraction.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/leakingabstraction.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/leakingabstraction.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/leakingabstraction.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/leakingabstraction.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/leakingabstraction.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/leakingabstraction.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/leakingabstraction.wordpress.com/59/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leakingabstraction.com&amp;blog=15814748&amp;post=59&amp;subd=leakingabstraction&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://leakingabstraction.com/2010/01/09/zend_db-query-fetch-methods-and-zend_db_select/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/992221ea094450d55784b1f95dd27753?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">andybaird</media:title>
		</media:content>

		<media:content url="http://www.zendframeworkhelp.com/wp-content/uploads/2010/01/table-select-all.png" medium="image">
			<media:title type="html">table-select-all</media:title>
		</media:content>

		<media:content url="http://www.zendframeworkhelp.com/wp-content/uploads/2010/01/table-select-row.png" medium="image">
			<media:title type="html">table-select-row</media:title>
		</media:content>

		<media:content url="http://www.zendframeworkhelp.com/wp-content/uploads/2010/01/table-select-column.png" medium="image">
			<media:title type="html">table-select-column</media:title>
		</media:content>

		<media:content url="http://www.zendframeworkhelp.com/wp-content/uploads/2010/01/table-select.png" medium="image">
			<media:title type="html">table-select</media:title>
		</media:content>
	</item>
		<item>
		<title>Using Zend_Db standalone</title>
		<link>http://leakingabstraction.com/2010/01/05/using-zend_db-standalone/</link>
		<comments>http://leakingabstraction.com/2010/01/05/using-zend_db-standalone/#comments</comments>
		<pubDate>Tue, 05 Jan 2010 22:01:47 +0000</pubDate>
		<dc:creator>Andy Baird</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[Zend_Db]]></category>

		<guid isPermaLink="false">http://www.zendframeworkhelp.com/?p=12</guid>
		<description><![CDATA[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&#8217;s go over the quick list of why it&#8217;s my fave: It automatically [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leakingabstraction.com&amp;blog=15814748&amp;post=12&amp;subd=leakingabstraction&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>If there is one class I had to pick out of the ZF library as the crown jewel, it would without a doubt be <a href="http://framework.zend.com/manual/en/zend.db.html">Zend_Db</a>.<br />
I rarely touch a PHP application or script that interacts with any database without utilizing this class.</p>
<p>Let&#8217;s go over the quick list of why it&#8217;s my fave:</p>
<ul>
<li>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)</li>
<li>It sanitizes data input for you automatically (as long as you use it correctly)</li>
<li>You can quickly grab results in array or object form without performing any post query operations.</li>
<li>Provides methods for programatically creating queries</li>
</ul>
<p>On top of that, it&#8217;s easily decoupled from the rest of the library. Let&#8217;s start out by ripping out Zend/Db.php and the Zend/Db folder and dropping it in our app.</p>
<h2>Initializing the database connection</h2>
<p>Now, in our settings / boilerplate file let&#8217;s initialize the database adapter. The database adapter uses a lazy connection (meaning it doesn&#8217;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.</p>
<pre>[ccew_php tab_size="4"]
$db = Zend_Db::factory('Pdo_Mysql', array(
	'host'             =&gt; 'localhost',
	'username'         =&gt; 'database_username',
	'password'         =&gt; 'database_password',
	'dbname'           =&gt; 'database'
));
[/ccew_php]</pre>
<p>That&#8217;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&#8217;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.</p>
<pre>[ccew_php]
require_once('Zend/Db/Table.php');
Zend_Db_Table::setDefaultAdapter($db);
[/ccew_php]</pre>
<p>And now within our classes or functions, we can easily call it at any time:</p>
<pre>[ccew_php]
class MyClass {
	private $db;
	function __construct() {
		$db = Zend_Db_Table::getDefaultAdapter();
	}
}
[/ccew_php]</pre>
<p>Presto. Persistent database object any time we need it in our application / script.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/leakingabstraction.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/leakingabstraction.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/leakingabstraction.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/leakingabstraction.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/leakingabstraction.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/leakingabstraction.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/leakingabstraction.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/leakingabstraction.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/leakingabstraction.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/leakingabstraction.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/leakingabstraction.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/leakingabstraction.wordpress.com/12/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/leakingabstraction.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/leakingabstraction.wordpress.com/12/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=leakingabstraction.com&amp;blog=15814748&amp;post=12&amp;subd=leakingabstraction&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://leakingabstraction.com/2010/01/05/using-zend_db-standalone/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/992221ea094450d55784b1f95dd27753?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">andybaird</media:title>
		</media:content>
	</item>
	</channel>
</rss>
