<?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/"
	>

<channel>
	<title>Dan Dean &#187; Code/Projects</title>
	<atom:link href="http://dandean.com/category/category/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://dandean.com</link>
	<description></description>
	<lastBuildDate>Wed, 12 May 2010 04:50:29 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Modulr: script concatination via CommonJS</title>
		<link>http://dandean.com/category/code/2010/modulr-script-concatination-via-commonjs/</link>
		<comments>http://dandean.com/category/code/2010/modulr-script-concatination-via-commonjs/#comments</comments>
		<pubDate>Thu, 15 Apr 2010 18:24:30 +0000</pubDate>
		<dc:creator>Dan Dean</dc:creator>
				<category><![CDATA[Code/Projects]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://dandean.com/?p=191</guid>
		<description><![CDATA[Modulr is a script concatenation tool I&#8217;ve been playing with which pre-processes client-side scripts into a single script suitable for deployment. This accomplishes two valuable goals: lets you break your scripts out into discreet chunks for functionality improves performance by minimizing the number of HTTP requests Example, assuming this hypothetical directory structure: - canvas --- [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://github.com/codespeaks/modulr" target="_blank">Modulr</a> is a script concatenation tool I&#8217;ve been playing with which pre-processes client-side scripts into a single script suitable for deployment. This accomplishes two valuable goals:</p>
<ul>
<li>lets you break your scripts out into discreet chunks for functionality</li>
<li>improves performance by minimizing the number of HTTP requests</li>
</ul>
<p></p>
<h3>Example, assuming this hypothetical directory structure:</h3>
<pre>
- canvas
--- tools.js
- color.js
- lang
--- enumerable.js
- main.js
</pre>
<p>The content of <tt>main.js</tt>:</p>
<pre class="brush: jscript;">
// Declare your dependencies and assign them to variables.
var color = require('color');
var ctools = require('canvas/tools');
var enumerable = require('lang/enumerable');

// Use your imported scripts!
var rgb = color.hex2rgb(&quot;#C00&quot;);
var myCanvas = ctools.attach(&quot;some-canvas-id&quot;);

enumerable.each([&quot;stuff&quot;, &quot;things&quot;, &quot;other&quot;], function(item, i) {
  // ...
});
</pre>
<p>As you can see, at the top of the file you simply <tt>require</tt> the scripts you&#8217;d like to use before using them. <em>That&#8217;s it, done!</em> Modulr takes care of fetching them and writing them into the file.</p>
<h3>Modulr avoids global-scope pollution</h3>
<p>Note that each <tt>require</tt> invocation assigns the result to a variable. The scripts which get concatenated via <tt>require</tt> are trapped within a closure, ensuring that your scripts do not pollute the global scope.</p>
<h3>Modulr makes your code more portable</h3>
<p>Another great thing about Modulr is that if follows the <a href="http://commonjs.org/" target="_blank">CommonJS API</a>, allowing you to declare your script dependencies in plain old JavaScript. No config files or embedded tokens, just JavaScript. This has the added benefit of making your scripts more portable &#8212; as long as your environment supports the CommonJS API (node, narwhal, etc) your scripts will know how to resolve their dependencies.</p>
<h3>Creating a CommonJS compatible module</h3>
<p>In order for a script to work with the CommonJS API it must assign public properties to the <tt>exports</tt> object.</p>
<p>The content of <tt>color.js</tt> illustrates this:</p>
<pre class="brush: jscript;">

// Define your functionality:
function hex2rgb(hex) {
  /* ... */
}

function rgb2hex(rgb) {
  /* ... */
}

// Attach your API to the exports object:
exports.hex2rgb = hex2rgb;
exports.rgb2hex = rgb2hex;
</pre>
<p></p>
<h3>A working example</h3>
<p>To get in and get your hands dirty, check out my working example up on Github. It&#8217;s very tiny, and attempts to get the core ideas through as simply as possible.</p>
<p><a href="http://github.com/dandean/modulr-demo" target="_blank">http://github.com/dandean/modulr-demo</a></p>
<p>Suggestions and corrections are always welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://dandean.com/category/code/2010/modulr-script-concatination-via-commonjs/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Installing Node.js on a Dreamhost Shared Server</title>
		<link>http://dandean.com/category/code/2010/installing-node-js-on-a-dreamhost-shared-server/</link>
		<comments>http://dandean.com/category/code/2010/installing-node-js-on-a-dreamhost-shared-server/#comments</comments>
		<pubDate>Fri, 09 Apr 2010 20:17:53 +0000</pubDate>
		<dc:creator>Dan Dean</dc:creator>
				<category><![CDATA[Code/Projects]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://dandean.com/?p=165</guid>
		<description><![CDATA[First, get the latest Node.js source onto your server. I keep my git downloads at ~/downloads/git. If it doesn&#8217;t already exist, create your download directories and cd into it: $ mkdir ~/downloads/git $ cd ~/downloads/git Then, pull down the latest Node.js source code from GitHub: $ git clone git://github.com/ry/node.git Since we&#8217;re on a Dreamhost shared [...]]]></description>
			<content:encoded><![CDATA[<p>First, get the <strong>latest <a href="http://nodejs.org/" target="_blank">Node.js</a> source</strong> onto your server. I keep my git downloads at <tt>~/downloads/git</tt>.</p>
<p>If it doesn&#8217;t already exist, create your download directories and <tt>cd</tt> into it:</p>
<pre>
  $ mkdir ~/downloads/git
  $ cd ~/downloads/git
</pre>
<p>Then, pull down the latest <a href="http://github.com/ry/node" target="_blank">Node.js source code from GitHub</a>:</p>
<pre>
  $ git clone git://github.com/ry/node.git
</pre>
<p>Since we&#8217;re on a Dreamhost shared server, we have to specify a personal directory for the node binaries to install to. This is because Dreamhost won&#8217;t allow us (for good reason) to install whatever we want into location which is shared by every other user on your server.</p>
<p>So, lets create our OWN <tt>/usr/local/bin</tt> directory:</p>
<pre>
  $ mkdir ~/usr/local/bin
</pre>
<p>Now that we&#8217;ve got that, let&#8217;s get into the node Git repo and configure node to use our new custom bin directory:</p>
<pre>
  $ ./configure --prefix=~/usr/local
</pre>
<p>If everything went well, <tt>make</tt> should handle the rest!</p>
<pre>
  $ make
  > ... a whole bunch of compilation output ...
  $ make install
  > ... more output ...
  > Done!
</pre>
<p>Now, you need to do one more thing to make node visible to your own scripts: add the new node binaries to your PATH! To do this you need to add the following line to two files in your home directory: <strong style="color:#f0f"><tt>.bashrc</tt></strong> and <strong style="color:#f0f"><tt>.bash_profile</tt></strong>.</p>
<pre>
  export PATH=$PATH:/home/[YOUR USER NAME]/usr/local/bin
</pre>
<p>You&#8217;re almost done! Just save both of those files, close your connection, reconnect, and check if you can run node! You should get something like this:</p>
<pre>
  $ node --version
  > v0.1.33-221-gff56d63
</pre>
<p><strong><em>Hot shit! Now go build some killer Node.js apps!</em></strong></p>
]]></content:encoded>
			<wfw:commentRss>http://dandean.com/category/code/2010/installing-node-js-on-a-dreamhost-shared-server/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>JavaScript Naming Conventions For People With Beards</title>
		<link>http://dandean.com/category/code/2010/javascript-naming-conventions-for-people-with-beards/</link>
		<comments>http://dandean.com/category/code/2010/javascript-naming-conventions-for-people-with-beards/#comments</comments>
		<pubDate>Tue, 09 Mar 2010 17:49:15 +0000</pubDate>
		<dc:creator>Dan Dean</dc:creator>
				<category><![CDATA[Code/Projects]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://dandean.com/?p=50</guid>
		<description><![CDATA[When developing in a team environment, coming to an agreed-upon set of naming conventions is incredibly important. The speed at which we as developers can come to comprehend the thought-processes and intentions of our peers greatly depends on our ability to look straight to their intentions, rather than having to first read the code line [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://dandean.com/wp-content/uploads/2010/03/dandean.jpg" alt="" title="Me and My Beard" width="80" class="alignleft size-full wp-image-155" style="float:left; margin: 0 10px 5px 0; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px;" />When developing in a team environment, coming to an <em>agreed-upon set of naming conventions</em> is incredibly important. The speed at which we as developers can come to comprehend the thought-processes and intentions of our peers greatly depends on our ability to look straight to their intentions, rather than having to first read the code line by line, mentally translating it into our own dialect, before truly understanding.</p>
<p>In short, <a href="http://twitter.com/Gaybeard" target="_blank">Aaron Cruz</a>, here is a quick summary of the naming conventions which I adhere to:</p>
<pre class="brush: jscript;">
var MyClass = Class.create({
  initialize: function(arg1, arg2) {
    this.publicProperty = &quot;'Public' property&quot;;
    this._privateProperty = &quot;'Private' property&quot;;
    var localVariable = null;
  },

  publicMethod: function() {
    return &quot;'Public' method&quot;;
  },

  isBooleanMethod: function() {
    return true;
  },

  _privateMethod: function() {
    return &quot;'Private' method&quot;;
  },

  __eventHandlerMethodClick: function(e) {
    return &quot;Click-event handler method&quot;;
  }
});

MyClass.classProperty = &quot;Class-level property&quot;;

MyClass.classMethod = function() {
  return &quot;Class-level method&quot;;
};

MyClass.MY_CLASS_CONSTANT = &quot;CONSTANT's should never change&quot;;

MyClass.ClassEnumOrSubType = {
  value0: 0,
  value1: 1,
  value2: 2,
  value3: 4,
  value4: 8
};
</pre>
<p>While the above example uses the <a href="http://api.prototypejs.org/" target="_blank">Prototype</a> class structure, none of the principles themselves are Prototype-specific.</p>
]]></content:encoded>
			<wfw:commentRss>http://dandean.com/category/code/2010/javascript-naming-conventions-for-people-with-beards/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>My Very Own GIT Manual</title>
		<link>http://dandean.com/category/code/2009/my-very-own-git-manual/</link>
		<comments>http://dandean.com/category/code/2009/my-very-own-git-manual/#comments</comments>
		<pubDate>Tue, 11 Aug 2009 21:59:05 +0000</pubDate>
		<dc:creator>Dan Dean</dc:creator>
				<category><![CDATA[Code/Projects]]></category>
		<category><![CDATA[git]]></category>

		<guid isPermaLink="false">http://dandean.com/?p=116</guid>
		<description><![CDATA[GIT confuses the hell out of me. I&#8217;m used to Subversion and Vault, and the translation isn&#8217;t always clear. Thankfully, there&#8217;s GitHub which makes it super easy to jump into using GIT. Unfortunately I constantly forget how to do simple tasks, not to speak of complex ones. This post is going to serve as my [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://git-scm.com/" target="_blank">GIT</a> confuses the hell out of me. I&#8217;m used to Subversion and Vault, and the translation isn&#8217;t always clear. Thankfully, there&#8217;s <a href="https://github.com/dandean" target="_blank">GitHub</a> which makes it super easy to jump into using GIT.</p>
<p>Unfortunately I constantly forget how to do simple tasks, not to speak of complex ones. This post is going to serve as my very own GIT manual so I can make these translations easily and not have to remember the intricacies.</p>
<h3>Updating your local repositories with remote changes: <tt> git pull</tt></h3>
<p>To get the latest changes from your remote repository merged into your local master, run <code>git pull</code>. This is pretty much the same as running <code>git fetch</code> then <code>git merge origin/master</code>. Think of this as the GIT version of <code>svn:update</code> or Vault&#8217;s &#8220;Get Latest&#8221;.</p>
<pre>
git pull
</pre>
<h3>Pushing local changes to your remote repository</h3>
<pre>
git add 'your file name'  #do this for each file or folder with changes
git commit -a -m 'Your commit message'
git push origin master
</pre>
<h3>Rejected!</h3>
<p>If a push to your remote repository gets rejected, it&#8217;s probably because remote files have been changed since you last used <tt>git pull</tt>. Run <tt>git pull</tt> then <tt>git push origin/master</tt> again. With any luck you should be in business.</p>
<p>Push master to origin/master</p>
<pre>
git push origin master
> To git@github.com:&lt;username&gt;/&lt;reponame>.git
>  ! [rejected]        master -> master (non-fast forward)
> error: failed to push some refs to 'git@github.com:&lt;username>/&lt;reponame>.git'
</pre>
<p>Damn! Shit&#8217;s broke! Pull again then re-try your push!</p>
<pre>
git pull
> Merge made by recursive.

git push origin master
> Counting objects: 10, done.
> Compressing objects: 100% (5/5), done.
> Writing objects: 100% (6/6), 814 bytes, done.
> Total 6 (delta 1), reused 0 (delta 0)
> To git@github.com:&lt;username>/&lt;reponame>.git
>    65a1527..79239e9  master -> master
</pre>
<p>It worked!</p>
<h3>Updating your fork of another user&#8217;s repository</h3>
<pre>
get fetch origin
git fetch upstream
git merge upstream/master
git push origin master
</pre>
<p>There&#8217;s probably an easier way to do that, but I haven&#8217;t figured out as of this writing.</p>
<h3>Counting the number of commits (and commiters)</h3>
<pre>
git shortlog -s -n
</pre>
<p>This just gives you a nice clean list. The best I can figure out is to clean it up with some regex and count it.</p>
<ul>
<li>Replace all letters and spaces with nothing: <code>[a-z ]+</code></li>
<li>Replace new lines with commas</li>
<li>Wrap the result in array delimiting square brackets</li>
<li>Count it up with JavaScript</li>
</ul>
<pre>
var commits = [744,536,68ö,39,17...1,1,1,1,1,1,1,1,1,1,1];
var count = 0;

commits.forEach(function(x) {
  count += x;
});
console.log(count);
</pre>
<p>If somebody has a better way, please tell me &#8212; this approach is overly complicated.</p>
]]></content:encoded>
			<wfw:commentRss>http://dandean.com/category/code/2009/my-very-own-git-manual/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Hatin&#8217; on textContent and innerText</title>
		<link>http://dandean.com/category/code/2009/hatin-on-textcontent-and-innertext/</link>
		<comments>http://dandean.com/category/code/2009/hatin-on-textcontent-and-innertext/#comments</comments>
		<pubDate>Tue, 02 Jun 2009 02:10:16 +0000</pubDate>
		<dc:creator>Dan Dean</dc:creator>
				<category><![CDATA[Code/Projects]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://dandean.com/?p=90</guid>
		<description><![CDATA[It&#8217;s surprisingly annoying to get just the text content of an html element in a cross-browser friendly way. I wrote Element#getTextContent() to take care of this simple operation for me. The Prototype Version: Element.addMethods({ /** * Element#getTextContent(@element) -&#62; String * Cross-browser means of getting Element#textContent or Element#innerText **/ getTextContent: function(element) { if (!Object.isUndefined(element.textContent)) { return [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s surprisingly annoying to get just the text content of an html element in a cross-browser friendly way. I wrote <code>Element#getTextContent()</code> to take care of this simple operation for me.</p>
<h3>The Prototype Version:</h3>
<pre class="brush: jscript;">
Element.addMethods({
  /**
   *  Element#getTextContent(@element) -&gt; String
   *  Cross-browser means of getting Element#textContent or Element#innerText
   **/
  getTextContent: function(element) {
    if (!Object.isUndefined(element.textContent)) {
      return element.textContent;
    }
    return element.innerText;
  }
});
</pre>
<h3>The Procedural Version</h3>
<pre class="brush: jscript;">
/**
 * Gets the text content of the specified element.
 * @param element {HTMLElement} The html element
 * @return {String} The string content of the specified element.
 */
function getTextContent(element) {
  if (typeof element.textContent != &quot;undefined&quot;) {
    return element.textContent;
  }
  return element.innerText;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://dandean.com/category/code/2009/hatin-on-textcontent-and-innertext/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Fluent: PHP Data Types as Fluent Objects</title>
		<link>http://dandean.com/category/code/2007/fluent-php-data-types-as-fluent-objects/</link>
		<comments>http://dandean.com/category/code/2007/fluent-php-data-types-as-fluent-objects/#comments</comments>
		<pubDate>Sun, 28 Oct 2007 16:19:09 +0000</pubDate>
		<dc:creator>Dan Dean</dc:creator>
				<category><![CDATA[Code/Projects]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://dandean.com/category/code/2007/fluent-php-data-types-as-fluent-objects/</guid>
		<description><![CDATA[Introducing Fluent, a set of PHP 5 classes that make writing code happier. Fluent enables you to deal with data types as objects in the fluent api style, like you can in most other modern programming languages. // JavaScript &#34;Hello There&#34;.toUpperCase().split(' '); // C# &#34;Hello There&#34;.ToUpper().Split(new Char[] {' '}); # Ruby &#34;Hello There&#34;.upcase.split(' ') # [...]]]></description>
			<content:encoded><![CDATA[<p>Introducing <strong>Fluent</strong>, a set of <a href="http://www.php.net/manual/en/language.oop5.php">PHP 5</a> classes that make writing code happier. Fluent enables you to deal with data types as objects in the <a href="http://www.alexatnet.com/node/98">fluent</a> <a href="http://www.travisswicegood.com/index.php/2007/10/26/fluent_api_here_i_come">api</a> style, like you can in most other modern programming languages.</p>
<pre class="brush: jscript; gutter: false;">
// JavaScript
&quot;Hello There&quot;.toUpperCase().split(' ');
</pre>
<pre class="brush: csharp; gutter: false;">
// C#
&quot;Hello There&quot;.ToUpper().Split(new Char[] {' '});
</pre>
<pre class="brush: ruby; gutter: false;">
# Ruby
&quot;Hello There&quot;.upcase.split(' ')
</pre>
<pre class="brush: python; gutter: false;">
# Python
&quot;Hello There&quot;.upper().split()
</pre>
<pre class="brush: php; gutter: false;">
// PHP
explode(' ', strtoupper('Hello There'));

// PHP using Fluent
S('Hello There')-&gt;toupper()-&gt;explode(' ');
</pre>
<p><span id="more-13"></span></p>
<h2>Fluent Data Types</h2>
<h3>OMG! &#8220;Strings!&#8221;</h3>
<p>Using the <strong>Fluent_String</strong> class you can chain your string manipulation functions together on to one line, much like a sentence.</p>
<pre class="brush: php;">
// Trim the white space from the left and right; Set to title case;
echo S('    fluent data type, huzaa!!   ')-&gt;trim()-&gt;ucwords();

// PRINTS: &quot;Fluent Data Type, Huzaa!!&quot;

// The same as above, but replace whitespace with 3 exclamations
echo S('    fluent data type, huzaa!!   ')-&gt;trim()-&gt;ucwords()
	-&gt;preg_replace(&quot;/s+/&quot;,'!!!');

// PRINTS: &quot;Fluent!!!Data!!!Type,!!!Huzaa!!&quot;;
</pre>
<h3>Neat, simple, arrays</h3>
<p>The <strong>Fluent_Array</strong> class works just like the above string class. Splice, shift, count, asort, whatever, at will.</p>
<pre class="brush: php;">
echo A(array('Bush','Clinton'))-&gt;splice(2,0,array('Bush','Clinton'))
	-&gt;push('Please stop now.');

// PRINTS: &quot;Bush, Clinton, Bush, Clinton, Please stop now.&quot;

echo A(array('Bush','Clinton'))-&gt;splice(2,0,array('Bush','Clinton'))
	-&gt;push('Please stop now.')-&gt;unique();

// PRINTS: &quot;Bush, Clinton, Please stop now.&quot;
</pre>
<h3>Numbers&#8230;</h3>
<p>Same goes for numbers, except that both <code>int</code> and <code>float</code> are handled within a single class: <strong>Fluent_Number</strong>.</p>
<pre class="brush: php;">
// Find the circumference of a circle which has a radius of 3.5cm
echo N(3.5)-&gt;times(2)-&gt;times(M_PI);

// PRINTS: 21.991148575129

// Find the radius of a circle based on circumference
echo N(21.991148575129)-&gt;divide(M_PI)-&gt;divide(2)-&gt;round(1);

// PRINTS: 3.5
</pre>
<h3>Boolean === Complete</h3>
<p>To round it out, the Boolean data type is also supported. This is in place for completeness, so that when you&#8217;re dealing with a Fluent object, you&#8217;re always returned a Fluent object.</p>
<pre class="brush: php;">
echo B(false);

// PRINTS: false
</pre>
<h3>Core Data</h3>
<p>You might have asked by now: &#8220;what if I <em>want the actual piece if data</em> instead of the Fluent object?&#8221; Well, the data at the core of every object is always available to you via the &#8216;value&#8217; property of the Fluent object, so it&#8217;s easy to leave the object behind and pass on the actual data.</p>
<pre class="brush: php;">
echo O(5)-&gt;value;

// PRINTS: 5
</pre>
<h2>Caveats</h2>
<p>There are, of course, some caveats that could trip you up, especially when dealing with numbers. For instance, if you try to directly add to Fluent_Number objects you&#8217;ll be given an E_NOTICE, the objects will be incorrectly &#8216;added&#8217;, and you&#8217;ll be sent on your way:</p>
<pre class="brush: php;">
echo $bad = N(10) + N(20);
Notice: Object of class Fluent_Number could not be converted to int

// PRINTS: 2
</pre>
<h3>Uncaveat</h3>
<p>The correct way is to use operators on the value of an object is to directly work on the <strong>core data</strong> of the object:</p>
<pre class="brush: php;">
echo $good = N(10)-&gt;value + N(20)-&gt;value; // return type = int
echo $good = N(10)-&gt;plus(20);             // return type = Fluent_Number

// PRINTS: 30
</pre>
<h2>Trans<em>mogrify</em> that shit</h2>
<p>It&#8217;s very common that a single piece of data will need to be different types of data at different points in your application. Fluent objects automatically and intelligently convert your object from one Fluent Data Type to the next based on the data type of the return value, so you won&#8217;t have to create new Fluent objects whenever your data changes form:</p>
<pre class="brush: php;">
echo O('President Bush is an evil bigot.')      // string
	-&gt;explode(' ')                          // array
	-&gt;splice(1,1,array('Cheney'))           // array
	-&gt;join(' ');                            // string

// PRINTS: President Cheney is an evil bigot.

echo O('President Bush is an evil bigot.')      // string
	-&gt;explode(' ')                          // array
	-&gt;splice(1,1,array('Cheney'))           // array
	-&gt;join(' ')                             // string
	-&gt;rev();                                // string

// PRINTS: .togib live na si yenehC tnediserP

echo O('President Bush is an evil bigot.')      // string
	-&gt;explode(' ')                          // array
	-&gt;splice(1,1,array('Cheney'))           // array
	-&gt;join(' ')                             // string
	-&gt;rev()                                 // string
	-&gt;len()                                 // int
	-&gt;times(19.5)                           // int
	-&gt;plus(3);                              // int

// PRINTS: 666
</pre>
<h2>Oh PHP, you&#8217;re so crazy.</h2>
<p>I can&#8217;t really say that PHP was the most <em>well</em> thought out thing in the world, and that&#8217;s probably because it wasn&#8217;t really thought out. PHP has adapted as a language as the web has grown and changed, which has enabled people of all skill level to get right in and create amazing tools. The language is incredibly simple but capable of astounding complexity.</p>
<p>This, of course, has its down side: when it comes to <strong>function names</strong>, <strong>function argument order</strong>, and <strong>function return values</strong> some crazy ass shit went down.</p>
<p>Fluent objects keep those unsightly stretch marks out of view by automatically shortening function names to their succinct names, among other things.</p>
<h3><code>array_splice()</code>, your name sucks</h3>
<p>If you&#8217;ve been looking closely you&#8217;ll have noticed that instead of <code>strtoupper()</code>, <code>strrev()</code> and <code>array_splice()</code> we&#8217;ve been using <code>splice()</code>, <code>toupper()</code> and <code>rev()</code>. This feature is universally applied to all functions with name prepended by &#8216;str&#8217;, str_&#8217; and &#8216;array_&#8217;.</p>
<h3>What kind of order is this?</h3>
<p>Another incredibly annoying thing about PHP is that there seems to be no logic to how the order of arguments was applied accross functions. The subject of the function, depending on the function, could be either the 1st, 2nd, or 3rd argument passed in.</p>
<p>With Fluent objects, the subject of the function is always the data within the Fluent object itself. This means that when you&#8217;re reading the documentation at php.net, remember that you should refrain from passing the subject as an argument&#8230; just pretend it doesn&#8217;t exist.</p>
<pre class="brush: php;">
// Normal sprintf
echo sprintf('Hello %s.','There');

// Fluent sprintf
echo S('Hello %s.')-&gt;sprintf('There');

// Multi-chained Fluent sprintf
echo S('Hello %s.')-&gt;sprintf('There %s')-&gt;sprintf('Sucka');

// Normal str_replace
echo str_replace(')','(','Sad :)');

// Fluent str_replace
echo S('Sad :)')-&gt;replace(')','(');
</pre>
<h3>What are you looking at?</h3>
<p>What makes Fluent objects so valuable is our ability to chain function calls together indefinitely. In order to do this we always need to have a handle on what we&#8217;re dealing with. PHP throws us for a loop here because many of the array functions require that the subject array be passed in as an argument <a href="http://docs.php.net/language.references.pass" title="Passing by Reference" target="_blank">by reference</a>, using the <code>&amp;</code> operator. This then modifies the array you passed in, and returns a result, which is in many cases <em>not</em> the modified array but a boolean &#8220;success&#8221; indicator, a portion of the original array, the length of the resulting array, and so on.</p>
<p>Our Fluent objects solve this problem by always returning the modified array while at the same time populating the <code>native</code> property of the Fluent object with the value usually returned by the native PHP function.</p>
<pre class="brush: php;">
$fruit = array('apple','orange','kiwi');
$result = array_push($fruit,'banana');

var_dump($fruit);

// PRINTS: array(4) {
//   [0]=&gt;string(5) &quot;apple&quot;
//   [1]=&gt;string(6) &quot;orange&quot;
//   [2]=&gt;string(4) &quot;kiwi&quot;
//   [3]=&gt;string(6) &quot;banana&quot;
// }

var_dump($result);
PRINTS: int(4)
</pre>
<p>Compare that to how a Fluent object behaves:</p>
<pre class="brush: php;">
$fruit = A(array('apple','orange','kiwi'))-&gt;push('banana');

var_dump($fruit-&gt;value);

// PRINTS: array(4) {
//   [0]=&gt;string(5) &quot;apple&quot;
//   [1]=&gt;string(6) &quot;orange&quot;
//   [2]=&gt;string(4) &quot;kiwi&quot;
//   [3]=&gt;string(6) &quot;banana&quot;
// }

var_dump($fruit-&gt;native-&gt;value);

// PRINTS: int(4)
</pre>
<h2>Shorter is Better</h2>
<p>I created these classes to make programming in PHP quicker and more elegant. For this reason you don&#8217;t have to use <code>new Fluent_String()</code> to start using the string class. You can if you want, of course, but each data type already has its own one letter shortcut function: <code>A()</code>, <code>S()</code>, <code>N()</code>, and <code>B()</code>.</p>
<p>There is also one more shortcut function for when you don&#8217;t care what you&#8217;re passing in, you just want it to be a Fluent object: <code>O()</code>. This function will take whatever it is you give it and return the appropriate Fluent data object.</p>
<h2>And&#8230;</h2>
<p>That&#8217;s basically it, really. Please <a href="http://dandean.com/wp-content/uploads/2007/10/fluent.zip" title="Fluent">download it and try it out</a>. If you do, let me know what you think, where it could be improved upon, and if there are any stupid bugs that I missed.</p>
<p>In the future I plan to deal with a couple outstanding issues. First I&#8217;ll update Fluent to allow you to provide your own data type classes to use instead of mine (or extended from mine). Also, an important part of proving the usefulness of Fluent will be to figure out how performant they are. So fairly soon you should be able to expect some benchmarks to compare function calls to their native incarnation.</p>
]]></content:encoded>
			<wfw:commentRss>http://dandean.com/category/code/2007/fluent-php-data-types-as-fluent-objects/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
