<?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>Advent Digerati &#187; PHP</title>
	<atom:link href="http://blog.adventdigerati.com/category/software/languages/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.adventdigerati.com</link>
	<description>Where Life meets Geek</description>
	<lastBuildDate>Mon, 26 Jul 2010 00:49:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Get Functional</title>
		<link>http://blog.adventdigerati.com/2010/07/get-functional/</link>
		<comments>http://blog.adventdigerati.com/2010/07/get-functional/#comments</comments>
		<pubDate>Thu, 08 Jul 2010 01:41:44 +0000</pubDate>
		<dc:creator>Zack</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://blog.adventdigerati.com/?p=73</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[<div style=text-align:center;font-style:italic;font-size:14px;">Sorry for the absence, it&#8217;s been a long road getting back here.</p>
<p>I hope you enjoy the ride.</p></div>
<p>Recently I&#8217;ve become fascinated with the concept of functional programming. For several years, I&#8217;ve had friends jump from language to language, but they all seem to settle on the functional side of the fence. &#8220;Why?&#8221; was the inevitable conundrum. For the longest time I couldn&#8217;t understand what it had to offer that you couldn&#8217;t do in other languages. Like most programming phenomena, it was an epiphanic moment that changed the way I looked at programming for the better forever.<br />
<span id="more-73"></span></p>
<h2>Code is Data; Data is Code</h2>
<p>Ok, omgwthbbq does <i>this</i> mean? How is code parseable data? How is data trustable code? For this, I had to rethink my stance on what makes a program an executable, not where the program comes from; it&#8217;s a cart-before-the-horse thing. So what makes a program? A program is executed lines of human-readable text compiled or interpreted but just the same converted into machine code before the processor reads the 1&#8242;s and 0&#8242;s from one stream and pushes a different set of 1&#8242;s and 0&#8242;s into another stream. Who cares how those lines got there. Could be from hand-entry, or it could be from a variable.<br />
<u>Epiphany the First: Who cares where we get code as long as it&#8217;s the right code we need?</u><br />
PHP has this: variable function names, <code lang="php">eval()</code>, <code lang="php">call_user_func()</code>. After you start coding using these patterns, it becomes nearly impossible to think otherwise. All of a sudden, &#8220;Gee, it would be so much easier if we could just tell functionY about functionX without having to teach classB about classA.&#8221; We stop thinking in terms of step-by-grudging-step and into segmented solutions to problems. When we can just <i>pass a function</i> into <code lang="php">functionY</code> of <code lang="php">classB</code>, this problem disappears. <code lang="php">classB</code> doesn&#8217;t have to give one darn about <code lang="php">classA</code>, just that when it needs to, it can use <code lang="php">functionX</code> and the world will keep on spinning.<br />
<u>Epiphany the Second: What data can I trust?</u><br />
Well, you can trust mine, silly! After all, I wrote it. Ah, so data doesn&#8217;t <i>have</i> to come from the user, it&#8217;s just a way of saying the A&#8217;s and underscores I put into the program can be used to reference other parts of the program without explicitly teaching them about each other. Data can come from anywhere, even code; and code can be executed from anything (with the right compiler/interpreter) including data.</p>
<p>Hopefully, this will spawn my first Git repository. Stay tuned for the linky!</p>
<p>[Edit July 7] Instead of a full-fledged repo, I just threw the PHP code up on <a href="http://bit.ly/9pyOh8" title="Gist">gist.github</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.adventdigerati.com/2010/07/get-functional/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>$c is not always $a[&quot;c&quot;]</title>
		<link>http://blog.adventdigerati.com/2009/04/c-is-not-always-ac/</link>
		<comments>http://blog.adventdigerati.com/2009/04/c-is-not-always-ac/#comments</comments>
		<pubDate>Thu, 02 Apr 2009 22:42:54 +0000</pubDate>
		<dc:creator>Zack</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Code Snippet]]></category>

		<guid isPermaLink="false">http://blog.adventdigerati.com/?p=48</guid>
		<description><![CDATA[Today I was tipped off to a certain quirk of PHP, specifically with how it handles Array resources. Every programmer knows, (or should know), the differences between creating a new copy of a variable and making a new reference to the same variable. In PHP, as far as I&#8217;ve known, you never access memory directly. [...]]]></description>
			<content:encoded><![CDATA[<p>Today I was tipped off to a certain <a href="http://blog.adventdigerati.com/2009/02/skill-and-quirks/">quirk</a> of PHP, specifically with how it handles Array resources. Every programmer knows, (or should know), the differences between creating a new copy of a variable and making a new reference to the same variable. In PHP, as far as I&#8217;ve known, you never access memory directly. Thus, trying <code>$v = "hello"; $a = &$v; $b = &$a;</code> does not make the value of <code>$b</code> a byte pointer to the location of <code>$a</code>, but instead a new <i>reference</i> to what <code>$v</code> holds. So, modifying <code>$b</code> means you will implicitly edit <code>$v</code>. To those familiar with PHP, this is understandable and often both acceptable and helpful. (As lazy programmers, we don&#8217;t want to have to remember when we have a reference or an &#8216;original&#8217; copy of a value.)</p>
<p>What I didn&#8217;t know, is that this could get us into a lot of trouble without even expecting it. The problem occurs whenever you try to obtain a reference to an element in a PHP array. Case in point:</p>
<pre>$a=Array("one"=>1, "two"=>2,"three"=>null);
$b = $a["four"];
$c =&#038; $a["five"];</pre>
<p>What do we get if we print the value of <code>$a</code> variables? <code>$a</code> is now
<pre>$a = Array(
  ["a"] => 1,
  ["b"] => 2,
  ["d"] => null,
  ["c"] => &#038;null
)</pre>
<p>WHAT?! What happened to <code>$b</code>? What in the world is a <i>pointer</i> to <code>null</code>? PHP actually created the &#8220;c&#8221; key within my Array, just by referencing it in a <i>read context</i>. Lesson learned: always use <code>isset($a["key"])</code> before attempting to draw from an Array by reference!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.adventdigerati.com/2009/04/c-is-not-always-ac/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Skill and Quirks</title>
		<link>http://blog.adventdigerati.com/2009/02/skill-and-quirks/</link>
		<comments>http://blog.adventdigerati.com/2009/02/skill-and-quirks/#comments</comments>
		<pubDate>Thu, 26 Feb 2009 03:30:17 +0000</pubDate>
		<dc:creator>Zack</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Theory]]></category>

		<guid isPermaLink="false">http://blog.adventdigerati.com/?p=42</guid>
		<description><![CDATA[As with any profession, programming is a split of skill and quirks. Quirks come in many forms and can be quite useful or a bane. In JavaScript, for instance, you can reference a function as an object, which itself can be referenced as a hash. Thusly, window.foo[bar](baz) is perfectly valid(!). In PHP, an Array can [...]]]></description>
			<content:encoded><![CDATA[<p>As with any profession, programming is a split of skill and quirks. Quirks come in many forms and can be quite useful or a bane. In JavaScript, for instance, you can reference a function as an object, which itself can be referenced as a hash. Thusly, <code>window.foo[bar](baz)</code> is perfectly valid(!). In PHP, an Array can be accessed by square or curly braces; <code>$a['b']</code> and <code>$a{'b'}</code> are equivalent(!!). These idiosyncrasies facilitate flexible code, yes, but can also be dangerous for maintenance. A person new to JavaScript, (who probably doesn&#8217;t quite grasp closures just yet), will most likely have less than a clue as to why the snipped is valid. The PHP programmer who has a background in C would expect the curly braces to define a new scope, not act as a hash lookup.</p>
<p>I am going to argue against myself here. I realize that in a prior <a href="http://blog.adventdigerati.com/2008/10/futureproof/">post</a> I praised PHP dereferencing, longing for the direct pointer manipulation of Perl, by using <code>$value=true; $name='value'; ${$name}==true</code>. However, for the next developer, he or she must understand prior to inheriting the code, how PHP handles inline eval() statements.</p>
<p>In situations where the use of these is unavoidable &ndash; usually in dynamically-created variables, LISP anyone? &ndash; a detailed comment is assuredly in order. Even if it is simple, an example, the next programmer to stumble across your code should be able to reasonably expect an outcome from the procedure.</p>
<p>In JavaScript I&#8217;ve been writing lately, I&#8217;ve become very cautious about the nature of functions and closures. Frequently, I&#8217;ve adopted the practice of namespacing everything I write. Because of that, grouping functions down to the program area can be tedious. No programmer wants to see <code>com.acme.financial.payment.forms.construct()</code>. With JavaScript, we can fake a <code>with()</code> statement. <code>var pay_form = com.acme.financial.payment.forms</code>; additionally <code>com.acme.financial[params['object_type']].forms[action](params_hash)</code> can save a lot of code later in the process.</p>
<p>As an engineer, we should always be looking for ways to perfect our trade. Often this means coding cleanly, and using conventions. Sometimes this means using quirks to their biggest advantage: shrinking the codebase. Remember, one bug for every ten lines.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.adventdigerati.com/2009/02/skill-and-quirks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>OOP-DBC</title>
		<link>http://blog.adventdigerati.com/2009/02/oop-dbc/</link>
		<comments>http://blog.adventdigerati.com/2009/02/oop-dbc/#comments</comments>
		<pubDate>Fri, 06 Feb 2009 05:03:47 +0000</pubDate>
		<dc:creator>Zack</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Code Snippet]]></category>

		<guid isPermaLink="false">http://blog.adventdigerati.com/?p=36</guid>
		<description><![CDATA[Coming out of high school, it was stressed that good practice makes good composition. One of these pillars of thought was code purity. Purity in the sense that each method should do as it&#8217;s advertised without causing side effects. It&#8217;s not much different than Design By Contract, (DBC) &#8211; a coding technique promoted in The [...]]]></description>
			<content:encoded><![CDATA[<p>Coming out of high school, it was stressed that good practice makes good composition. One of these pillars of thought was code purity. Purity in the sense that each method should do as it&#8217;s advertised without causing side effects.</p>
<p>It&#8217;s not much different than Design By Contract, (DBC) &ndash; a coding technique promoted in <a href="http://www.pragprog.com/titles/tpp/the-pragmatic-programmer">The Pragmatic Programmer</a>, another book I&#8217;m reading for work. The thought is that every method has a contract to which it and other methods &ndash; and in OOP, objects/classes &ndash; abide by. Everyone fulfills their contract, everyone benefits, and the programmer can go home early that night.</p>
<p>The downside, as T.P.P. describes, is that OOP does not lend itself nicely to automatic DBC programming: namely that method inheritance doesn&#8217;t imply contract inheritance. This seems like a relatively small gripe to be made about OOP, in my opinion, especially when a simple coding standard can surmount this problem.</p>
<p>In what I&#8217;ve learned from OOP, good style is to use both public and private methods, and methodologies, to their advantage. This, thankfully, lends itself well to implementing DBC.</p>
<p>As with most of my posts, this one includes an example!</p>
<pre>/**
 * Basic object class, all other classes should extend this
 */
class BaseObject {
    /**
     * Public accessor to the toString() concept
     */
    public function toString() {
        // contract invariants
        $invariants = Array('this'=>$this);
        // contract presumptions
        assert(is_object($this), get_type($this)." is not an Object");

        // inherited method
        $r_val = $this->_toString();

        // contract post assertions
        assert(equals($invariants['this'], $this), get_class($this)."::toString() modified the Object in a read-only context");
        assert(is_string($r_val), get_class($this)."::toString() did not return a String.");

        return $r_val;
    }

    /**
     * Private implementation of the toString() concept
     */
    private function _toSring() {
        $r_val = Array();
        $r_val[] = $this->some_val;

        return implode("\n", $r_val);
    }
}

/**
 * A class which does what it's supposed to do
 */
class GoodObject extends BaseObject {
    /**
     * This function abides by the BaseObject::toString() contract
     */
    public function _toString() {
        $r_val = Array();
        $r_val[] = $this->some_val;
        $r_val[] = $this->other_val;

        return implode("\n", $r_val);
    }
}

/**
 * A mischevious class
 */
class BadObject extends BaseObject {
    /**
     * This function does not abide by the BaseObject::toString() contract
     */
    public function _toString() {
        $r_val = Array();
        $r_val[] = $this->yet_another_val;
        $r_val[] = $this->some_val;

        return $r_val;
    }
}</pre>
<p>So we can see that it&#8217;s not too hard to notice that the assertions set in place in the <code>BaseObject</code> class will catch whatever the contract for toString() has been set up. Better even than that, the contract can be amended in <u>one place</u> and it will filter down throughout all subclasses. It&#8217;s OOP-DBC; and it could save your life &ndash; or at least your program.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.adventdigerati.com/2009/02/oop-dbc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dynamic-SQL Act II</title>
		<link>http://blog.adventdigerati.com/2008/12/dynamic-sql-act-ii/</link>
		<comments>http://blog.adventdigerati.com/2008/12/dynamic-sql-act-ii/#comments</comments>
		<pubDate>Fri, 05 Dec 2008 05:19:25 +0000</pubDate>
		<dc:creator>Zack</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Practicum]]></category>

		<guid isPermaLink="false">http://blog.adventdigerati.com/?p=16</guid>
		<description><![CDATA[In my last post, I set the stage for a miniseries of posts regarding dynamic SQL construction. This is a problem many software vendors face: Allowing the user direct-access to the database is a huge red flag, and one many engineers strain to avoid. Should there be no alternative, however, great care should be allotted [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://blog.adventdigerati.com/2008/11/dynamic-sql-act-i/trackback/">last post</a>, I set the stage for a miniseries of posts regarding dynamic SQL construction. This is a problem many software vendors face: Allowing the user direct-access to the database is a <i>huge</i> red flag, and one many engineers strain to avoid. Should there be no alternative, however, great care should be allotted in making the users&#8217; experience as friendly as possible, (while, of course, keeping the user safe from dismantling their own data).</p>
<p>Typically for relational database schemas, (RDb&#8217;s), this results in a tree-generating interface which abstracts the actual syntax away from the user. In theory, it&#8217;s an excellent way to afford the power user the ability to generate near-infinite custom reporting tools and also help bug-fixing by relying on a few, axiomatic functions.</p>
<p>This doesn&#8217;t come without cost, however. Since a relational database is, by definition, segregated into distinct entities, it can be difficult for a program to discern which relationship between two entities to choose. This decision can be critical and time-sensitive for a user. As mentioned in the previous post, if a Person can choose a Profession to be a Painter or a Plumber but not both, then software which attempts to offer criteria based on these relationships should be contextually aware of what the user is asking for.</p>
<p>Most often, problems like these are kept to a minimum by not offering choices too complex for the system to evaluate in a reasonable time. For instance, let&#8217;s continue our previous example and introduce two new entities/tables called <code>Baby</code> and <code>Ghost</code>. These have the relationships &#8220;A <code>Baby</code> grows up to be a <code>Person</code>&#8221; and &#8220;A <code>Person</code> can die and become a <code>Ghost</code>.&#8221; For our system, we would like to hide the fact that between the Person and Ghost steps, the person who dies must be listed as <code>Deceased</code>. This is much the same as we do not store the Person&#8217;s profession as a line-item, but rather as a separate listing &ndash; perhaps with dates they started and ended a particular job. To the user, the details should be available but not mandatory, and requiring the Deceased entry could be an undue hastle and cost precious processing time.</p>
<p>Thusly, our system has to be quite intelligent. It must realize that the <code>Baby</code> becomes a <code>Person</code>, which can obtain none or many <code>Profession</code>s, will become <code>Deceased</code>, and could be believed to return as a <code>Ghost</code>. To keep the system under control, an interface is often limited to entities only two relationships, (&#8220;two-hops&#8221;), away from those already specified. Keeping up with our requirement for interface ease-of-use, the next logical step is to define a way to recursively discern these two-hop relationships and offer the user a means to resolve conflicts or ambiguous decisions. In so doing, we could offer the <code>Baby</code> and <code>Ghost</code> entities, (a four-hop relationship), from the start.</p>
<p>The question then becomes, &#8220;What tools will we need to perform such an operation?&#8221; Handily enough, I believe we have the capability, even on the Web, with JavaScript and proper algorithm implementation.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.adventdigerati.com/2008/12/dynamic-sql-act-ii/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Future Proof</title>
		<link>http://blog.adventdigerati.com/2008/10/futureproof/</link>
		<comments>http://blog.adventdigerati.com/2008/10/futureproof/#comments</comments>
		<pubDate>Tue, 07 Oct 2008 05:18:40 +0000</pubDate>
		<dc:creator>Zack</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Code Snippet]]></category>

		<guid isPermaLink="false">http://adventtechnorati.wordpress.com/?p=8</guid>
		<description><![CDATA[Can we reference an algorithmically-named set of variables in one variable to make our PHP code as future proof as possible? Yes we can!]]></description>
			<content:encoded><![CDATA[<p>In every codebase you run into unique challenges. Space and time complexity are the enterprise programmer&#8217;s nemeses, and all too often appear as cousins to another problem: extensibility.</p>
<p>The problem with making anything a solitary factor more expandable is that it increases the complexity required to interface with that feature by at least twice that factor &mdash; twice in the sense that time and complexity, remember them?, are lower-bounded to being capable of handling the expansion.</p>
<p>Case in point: The difference between a pre-populated list and one whose values are variant depending on which portions of a codebase are considered &#8220;active.&#8221; This can pose quite the problem depending on how mission-critical this list is. (After all, this is a science; and all science should be repeatable <i>ad infinity</i>.) But how to retain this ability to accept a near-infinite range of values and manage them in some human-readable way?</p>
<p>Here we find the strengths and weaknesses of a language. In C, everything you touch is memory whether you realize it or not. From byte-pointers to malloc-ed blocks of hard disk, C keeps you up to your elbows in references. Perl scales the complexity back by a good factor, but grabbing references is still do-able: <code>$ref = \$scalar</code> is a direct accessor to the memory allocated by <code>$scalar</code>; and conversely, <code>$val = $$ref</code> gets the value of whatever variable resides at the memory location <code>$ref</code>. Pretty handy if you have an unknown-length set of variables with similar names. Now we have a common variable name we can manipulate without having a half-dozen Eval() functions in our code. (Aside: Eval() is nice, but sneakily evil; it&#8217;s slow, offers arbitrary code execution if use improperly, and just plain ugly.) Our syntax highlighters can show us exactly what we meant, and in six months when we&#8217;ll use this as the basis for the program&#8217;s next feature, we&#8217;ll have a much clearer idea of what the hell we wanted to get out of it.</p>
<p>But this is Perl. How do we do this in a language which masks references like PHP? Unfortunately, we can&#8217;t go flying around the memory stack as easily as Perl does, but we can get pretty close with a single Eval(). (Aside 2: I know, I just got done bashing Eval(); I haven&#8217;t forgotten, but we&#8217;re in control of the string this code evaluates, so take a breath.)</p>
<p>PHP offers an arguably more elegant Eval() than most languages, the <a href="http://www.google.com/codesearch?q=lang%3Aphp%20%22%24{%24%22&amp;btnG=Search+Code">inline eval</a>. So let&#8217;s reassume our situation: an unknown number of similarly-named variables is in our module&#8217;s scope and we want an elegant, memorable way to access their values for modulation.<br />
In Perl:</p>
<pre><code>$value_1 = "some important value";
for($i=1; $i &lt; $some_known_upper_bound; $i++) {
    $value_variable_name = "value_" . $i;
    $value = $$value_variable_name;
    # some modulator code
}</code></pre>
<p>In PHP:</p>
<pre><code>$value_1 = "some important value";
for($i = 1; $i &lt; $some_known_upper_bound; $i++) {
    $value_variable_name = "value_" . $i;
    # the magic...
    $value = ${$value_variable_name};
    # some modulator code
}</code></pre>
<p>And there you have it. Future proof code that modifies a like-named set of variables with a single, easily understood and aptly named variable.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.adventdigerati.com/2008/10/futureproof/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
