<?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>Drew C King</title>
	<atom:link href="http://drewcking.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://drewcking.com</link>
	<description>Code and stuff</description>
	<lastBuildDate>Fri, 12 Aug 2016 21:10:07 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.4.8</generator>
	<item>
		<title>Fixin&#8217; PCs for Fun and/or Profit</title>
		<link>http://drewcking.com/2016/08/fixin-pcs-for-fun-andor-profit/</link>
		<pubDate>Fri, 12 Aug 2016 21:10:07 +0000</pubDate>
		<dc:creator><![CDATA[drew]]></dc:creator>
				<category><![CDATA[General Tech]]></category>

		<guid isPermaLink="false">http://drewcking.com/?p=397</guid>
		<description><![CDATA[To make sure your PC is working properly, you must take care of it. And fix it when it breaks. Perhapsbuy a new one if it&#8217;s broken badly.]]></description>
				<content:encoded><![CDATA[<p><a href="http://drewcking.com/wp-content/uploads/2016/08/pc.jpg" rel="attachment wp-att-398"><img class="alignnone size-medium wp-image-398" src="http://drewcking.com/wp-content/uploads/2016/08/pc-300x192.jpg" alt="pc" width="300" height="192" srcset="http://drewcking.com/wp-content/uploads/2016/08/pc-300x192.jpg 300w, http://drewcking.com/wp-content/uploads/2016/08/pc-768x492.jpg 768w, http://drewcking.com/wp-content/uploads/2016/08/pc-624x399.jpg 624w, http://drewcking.com/wp-content/uploads/2016/08/pc.jpg 800w" sizes="(max-width: 300px) 100vw, 300px" /></a><br />
To make sure your PC is working properly, you must take care of it. And fix it when it breaks. Perhapsbuy a new one if it&#8217;s broken badly.</p>
]]></content:encoded>
			</item>
		<item>
		<title>Testing fb 1</title>
		<link>http://drewcking.com/2016/07/testing-fb-1/</link>
		<pubDate>Thu, 28 Jul 2016 15:23:18 +0000</pubDate>
		<dc:creator><![CDATA[drew]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://drewcking.com/?p=394</guid>
		<description><![CDATA[body goes here]]></description>
				<content:encoded><![CDATA[<p>body goes here</p>
]]></content:encoded>
			</item>
		<item>
		<title>Enumerated Constants in PHP with Namespaces</title>
		<link>http://drewcking.com/2012/10/enumerated-constants-in-php-with-namespaces/</link>
		<pubDate>Sat, 20 Oct 2012 17:10:29 +0000</pubDate>
		<dc:creator><![CDATA[drew]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://drewcking.com/?p=224</guid>
		<description><![CDATA[A few years ago, I wrote up an entry (Pseudo-enum in PHP) describing how to mimic enum types, like in C++. C/C++: As mentioned in my older blog post, there&#8217;s no such native enum type or function in PHP, but you can make clever use of array_flip(), apc_define_constants() and apc_load_constants() to ultimately get the same [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>A few years ago, I wrote up an entry (<a href="http://drewcking.com/2008/08/pseudo-enum-in-php/">Pseudo-enum in PHP</a>) describing how to mimic <samp>enum</samp> types, like in C++.</p>
<p><em>C/C++</em>:</p>
<pre class="brush: cpp; title: Source Code; notranslate">
#define ADMIN     0
#define MODERATOR 1
#define EDITOR    2

// ... same thing, but less typing...
enum { ADMIN, MODERATOR, EDITOR };

// ... regardless, now you can do ...
int myRole = ADMIN;
</pre>
<p><span id="more-224"></span><br />
As mentioned in my older blog post, there&#8217;s no such native <samp>enum</samp> type or function in PHP, but you can make clever use of <samp><a href="http://www.php.net/array_flip" target="_blank">array_flip()</a></samp>, <samp><a href="http://www.php.net/apc_define_constants" target="_blank">apc_define_constants()</a></samp> and <samp><a href="http://www.php.net/apc_load_constants" target="_blank">apc_load_constants()</a></samp> to ultimately get the same effect. </p>
<p>I finished that old post wanting more, though, namely the ability to specify a namespace into which to define these enumerated constants. This was back in 2008, and I had no clue at the time how namespaces would be implemented in PHP. This has been a reality ever since PHP 5.3 came out, and so I decided to re-tool my previous approach.</p>
<p>To reiterate the problem: I want to specify nothing more than a set of strings, and end up with enumerated constants, with the option of putting them all in an arbitrary namespace to avoid name collisions.</p>
<p>BEHOLD! <samp>my_apc_enum()</samp> using PHP 5.4&#8217;s wonderful new short array syntax:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
    /**
     * Try loading a set of constants from APC, otherwise
     * define them and store them into APC.
     */
    $key       = 'roles';
    $constants = ['ADMIN','MODERATOR','EDITOR'];

    my_apc_enum($key, $constants);

    echo &quot;Admin: &quot;     . ADMIN;     // Admin: 0
    echo &quot;Moderator: &quot; . MODERATOR; // Moderator: 1
    echo &quot;Editor: &quot;    . EDITOR;    // Editor: 2

    /**
     * OR you can put them all in a namespace
     */
    $key       = 'blogRoles';
    $constants = ['ADMIN','MODERATOR','EDITOR'];
    $namespace = 'blog';

    my_apc_enum($key, $constants, $namespace);

    echo &quot;Admin: &quot;     . blog\ADMIN;     // Admin: 0
    echo &quot;Moderator: &quot; . blog\MODERATOR; // Moderator: 1
    echo &quot;Editor: &quot;    . blog\EDITOR;    // Editor: 2

</pre>
<p>Another neat way to quickly see all constants you&#8217;ve defined, whether explicitly using <samp><a href="http://www.php.net/define" target="_blank">define()</a></samp> one constant at a time, or using <samp><a href="http://www.php.net/apc_define_constants" target="_blank">apc_define_constants()</a></samp>, is to use <samp><a href="http://www.php.net/get_defined_constants" target="_blank">get_defined_constants()</a></samp>:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
    // array dereferencing! if you have PHP 5.4 ...
    print_r(get_defined_constants(true)['user']);

    // PHP 5.3 and below, you gotta do ...
    $constants = get_defined_constants(true);
    print_r($constants['user']);
</pre>
<p>Anyway, here&#8217;s how <samp>my_apc_enum()</samp> is implemented:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
function my_apc_enum($key, $constants, $namespace = null) {

    // try loading the constants from APC
    if (!apc_load_constants($key)) {
    
        // was a namespace specified?
        if (!empty($namespace)) {
	    	
            // yep! prepend the namespace onto each constant name
            foreach ($constants as &amp;$c) {
                $c = $namespace . '\\' . $c;
            }
        }

        // make APC define them all
        apc_define_constants($key, array_flip($constants));

        // APC cache miss :-(
        return false;
    }

    // APC cache hit :-)
    return true;
}
</pre>
]]></content:encoded>
			</item>
		<item>
		<title>Chained Request Handlers with Closures</title>
		<link>http://drewcking.com/2009/09/chained-request-handlers-with-closures/</link>
		<pubDate>Wed, 02 Sep 2009 09:40:06 +0000</pubDate>
		<dc:creator><![CDATA[drew]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Comb]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://drewcking.com/?p=72</guid>
		<description><![CDATA[One of the problems with naming request handlers to match the incoming request method, e.g., GET, POST, PUT, DELETE, is that there&#8217;s an obvious potential for accidentally re-declaring that function. At this point in time, there are no pre-existing functions in PHP core that are named get(), post(), put(), delete(), head(), options(), trace(), or connect(), [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>One of the problems with naming request handlers to match the incoming request method, e.g., GET, POST, PUT, DELETE, is that there&#8217;s an obvious potential for accidentally re-declaring that function. At this point in time, there are no pre-existing functions in PHP core that are named <samp>get()</samp>, <samp>post()</samp>, <samp>put()</samp>, <samp>delete()</samp>, <samp>head()</samp>, <samp>options()</samp>, <samp>trace()</samp>, or <samp>connect()</samp>, but that&#8217;s no guarantee that there won&#8217;t be in the future, or in a 3rd party extension/library that you may be using.</p>
<p>To get around that potential name collision, I could do a few things:<br />
<span id="more-72"></span></p>
<ul>
<li>Have a fixed prefix for those functions, e.g., <samp>doget()</samp>, <samp>dopost()</samp>, etc</li>
<li>Have a user specified prefix that defaults to &#8220;&#8221;, so you could write your app with <samp>get()</samp>, <samp>post()</samp>, etc, or specify &#8220;do&#8221; in the init and use <samp>doget()</samp>, <samp>dopost()</samp>, or maybe specify &#8220;_&#8221; and use <samp>_get()</samp>, <samp>_post()</samp>, etc.</li>
<li>Require the requested script to define a specific class with static methods for those HTTP verbs (with or without prefixes).</li>
</ul>
<p>I wasn&#8217;t really satisfied with any of these options though. Prefixing the function names makes it less likely that a fatal function redeclaration would occur down the line, but technically it&#8217;s not impossible. That&#8217;s where the dynamic prefixing comes in: it makes it easier to sort of move those functions out of the line of fire, but they&#8217;re still on the battlefield. I&#8217;d rather extract them from combat altogether, so to speak.</p>
<p>The cleaner solution of those three options, IMO, would be to define a single class in every single one of the requested scripts. Something like:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
class comb_handler 
{
    public static function get()    { ... }
    public static function post()   { ... }
    public static function put()    { ... }
    public static function delete() { ... }
}
</pre>
<p>Then Comb would just check to see of the requested method exists, and run it if so. While that would pretty much solve the function name collision problem, it feels very hackish to me. You&#8217;d essentially be using a class for nothing more than its namespace. After considering that for a bit, I remembered that PHP 5.3 introduced closures. So instead of the request script looking like this:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
function get() 
{
    echo &quot;hi&quot;;
}
</pre>
<p>I could do this:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
comb_handle('get', function() 
{
    echo &quot;hi&quot;;
});
</pre>
<p>What I like about this approach is that instead of defining a specific request handler, I can define a bunch of them as closures and have <samp>comb_handle()</samp> just stick them all in an array, called <samp>$method_chains</samp>. Then when it comes time to run the request methods, I can just loop over that array of closures and run them one after another. <samp>comb_handle()</samp> would look something like:</p>
<pre class="brush: php; title: Source Code; notranslate"> 
function comb_handle($http_method, $closure)
{
    /**
     *  if comb were an extension, this variable would 
     *  only be accessible within the extension itself.
     *
     * $method is one of GET, POST, PUT, DELETE, XHR
     */
    global $method_chains;
    $method_chains[strtolower($http_method)][] = $closure;
}
</pre>
<p>So imagine a GET request comes in for <samp>/session/login.php</samp>. The following scripts would get included (if they all exist):</p>
<pre class="brush: plain; highlight: [3]; title: Source Code; notranslate">
/prepend.php
/session/prepend.php
/session/login.php
/session/append.php
/append.php
</pre>
<p>In each of those scripts, you can define handlers for any request method you want. To illustrate this, you could do the following in each of the scripts above:</p>
<pre class="brush: php; title: Source Code; notranslate">
/* /prepend.php */
&lt;?php
comb_handle('get', function() {
    echo &quot;one! &quot;;
});
 
/* /session/prepend.php */
&lt;?php
comb_handle('get', function() {
    echo &quot;two! &quot;;
});
 
/* /session/login.php */
&lt;?php
comb_handle('get', function() {
    echo &quot;three! &quot;;
});
 
/* /session/append.php */
&lt;?php
comb_handle('get', function() {
    echo &quot;four! &quot;;
});
 
/* /append.php */
&lt;?php
comb_handle('get', function() {
    echo &quot;five! &quot;;
});

</pre>
<p>Then after Comb includes those scripts the <samp>$method_chains</samp> array will look like:</p>
<pre class="brush: php; title: Source Code; notranslate">
array(1) {
  [&quot;get&quot;]=&gt; array(5) {
    [0]=&gt; object(Closure)#1 (0) {}
    [1]=&gt; object(Closure)#2 (0) {}
    [2]=&gt; object(Closure)#3 (0) {}
    [3]=&gt; object(Closure)#4 (0) {}
    [4]=&gt; object(Closure)#5 (0) {}
  }
}
</pre>
<p>Comb would simply do a foreach over <samp>$method_chains[&#8216;get&#8217;]</samp> calling each closure, and you&#8217;d see this in your browser:</p>
<pre class="brush: plain; title: Source Code; notranslate">
one! two! three! four! five!
</pre>
<p>So that&#8217;s the direction I&#8217;m heading now. That obviously means that Comb will require PHP 5.3 from this point forward, but another advantage of doing so is using namespaces to clean up these ugly comb_* prefixed functions. Some folks might not agree, but to me, this:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
use comb as c;
c\handle('get',  function() {});
c\handle('post', function() {});
</pre>
<p>feels cleaner (though weirder) than:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
comb_handle('get',  function() {});
comb_handle('post', function() {});
</pre>
<p>Might as well start getting used to using namespaces though. They&#8217;ll be getting much more common over the next couple of years.</p>
]]></content:encoded>
			</item>
		<item>
		<title>A Procedural Version of Comb</title>
		<link>http://drewcking.com/2009/08/a-procedural-version-of-comb/</link>
		<pubDate>Sun, 16 Aug 2009 01:46:46 +0000</pubDate>
		<dc:creator><![CDATA[drew]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Comb]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://drewcking.com/?p=99</guid>
		<description><![CDATA[I think this is the third time I&#8217;ve re-tooled the guts of Comb. The main idea is still the same, but the default behavior is a little different, and it&#8217;s not object-oriented at all. My goal in doing it this totally procedural way is to make it possible to build it as a PHP extension, [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>I think this is the third time I&#8217;ve re-tooled the guts of Comb. The main idea is still the same, but the default behavior is a little different, and it&#8217;s not object-oriented at all. My goal in doing it this totally procedural way is to make it possible to build it as a PHP extension, thus configuring its default behavior via httpd.conf, .htaccess, or php.ini. Not that making it an extension means that I <em>can&#8217;t</em> use objects. I just didn&#8217;t really feel the need at this point. Unsurprisingly, I may change my mind later :-/<br />
<span id="more-99"></span></p>
<h2>Setup &#038; Configuration</h2>
<p>Comb still runs using the same overall lifecycle process as before, and at this point you still need to auto_prepend_file that bootstrap script. So your vhost would look pretty basic:</p>
<pre class="brush: plain; title: Source Code; notranslate">
&lt;VirtualHost *:80&gt;
    ServerName example.com
    DocumentRoot /sites/example.com/www
 
    &lt;Directory /sites/example.com/www&gt;
        Options -Indexes, FollowSymLinks
        AllowOverride All
    &lt;/Directory&gt;
&lt;/VirtualHost&gt;
</pre>
<p>/sites/example.com/www/.htaccess would contain:</p>
<pre class="brush: bash; title: Source Code; notranslate">
php_value auto_prepend_file &quot;/sites/example.com/bootstrap.php&quot;
</pre>
<p>and /sites/example.com/bootstrap.php looks like:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
    // comb_* functions are all defined in here...
    require '/www/example.com/comb.php';
 
    /**
     * set config values via php
     * ...or in .htaccess using php_value, if comb was 
     * built as an extension. (someday!)
     */
    $opt = array();
    comb_init($opt);
 
    // find includes, run REQUEST_METHOD function, eg, get(), post()
    comb_run();
 
    // render templates if enabled
    comb_render();
 
    // send headers, flush buffer
    comb_send();
</pre>
<p>That first comb.php that&#8217;s being included is the library itself, and would ideally just get loaded as an extension. Even this bootstrap script would be written into the extension and run implicitly if it&#8217;s enabled for the vhost. But until I get brave enough to learn how in the world to translate this stuff into C, it&#8217;s going to have to exist in PHPland.</p>
<h2>Application code</h2>
<p>So now we write a &#8220;web application&#8221; that runs on Comb. I&#8217;ll create the following file in the document root called index.php:</p>
<pre class="brush: xml; title: Source Code; notranslate">
&lt;h1&gt;hello, world!&lt;/h1&gt;
</pre>
<p>That will do exactly what you think it does: a big bold howdy. As will this:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
    echo &quot;&lt;h1&gt;hello, world!&lt;/h1&gt;&quot;;
</pre>
<p>And actually, this will too:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
function get()
{
    echo &quot;&lt;h1&gt;hello, world!&lt;/h1&gt;&quot;;
}
</pre>
<p>And this is where it gets interesting; that get() function was defined, but I obviously didn&#8217;t call it explicitly. That&#8217;s done automatically in the comb_run() function. If a function exists that matches the incoming request method, it&#8217;ll get called, otherwise any output that&#8217;s sent will either get buffered and plugged into a template during rendering (if buffering is enabled), or immediately sent back to the client (if buffering is disabled).</p>
<h2>Templating</h2>
<p>Templating is also automatic. You can change index.php to be:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
function get()
{
    // assign a var to be extracted into the template
    comb_set('title', 'hello, world!');
}
</pre>
<p>then create a new file beside it in the document root called index.tpl.php:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;h1&gt;&lt;?=$title?&gt;&lt;/h1&gt;
</pre>
<p>That template file gets detected automatically in the comb_render() function, basically by looking for a file whose name is {script_basename}{template_extension}. The default template extension is set to .tpl.php but that&#8217;s configurable, so you can set it to .tpl or .phtml or whatever you&#8217;re accustomed to.</p>
<p>For shared templates (e.g., header &#038; footer), a common practice is to explicitly include them in each template that uses them, like:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php include &quot;header.tpl.php&quot;; ?&gt;
 
&lt;h1&gt;&lt;?=$title?&gt;&lt;/h1&gt;
 
&lt;?php include &quot;footer.tpl.php&quot;; ?&gt;
</pre>
<p>which makes you end up with a lot of code duplication if you have many templates using that header/footer combo. I&#8217;m personally fond of the layout approach, i.e., a single wrapper template that plugs the wrapped content into place. To accomplish that, output buffering is critical, and there has to be some mechanism in place in the layout template to grab the contents of the buffer. For that, there’s the comb_buffer() function. It&#8217;s used like so, in a new template file (also in the document root) called layout.tpl.php:</p>
<pre class="brush: xml; title: Source Code; notranslate">
&lt;html&gt;
&lt;body&gt;
Header stuff
 
&lt;div&gt;&lt;?php echo comb_buffer(); ?&gt;&lt;/div&gt;
 
Footer stuff
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>This will take the output rendered by index.tpl.php and drop it into that div. No need to include anything within the requested template. The comb_render() function not only auto-detects the requested template based off the requested script&#8217;s basename, but it also auto-detects the layout. If {layout_name}{template_extension} doesn&#8217;t exist (both configurable, &#8220;layout&#8221; and &#8220;.tpl.php&#8221; are the defaults), it simply won&#8217;t get wrapped.</p>
<h2>Directory-Based Filtering</h2>
<p>One of my primary goals with Comb is to keep the application simple by relying on as much web server work as I reasonably can. Organizing the application in simple, reasonably-named directories makes this very easy, because there&#8217;s no need for an explicit dispatch method that 1) parses the request URI, 2) processes user-defined routes to find a matching controller/handler, 3) instantiates and runs the controller/handler.</p>
<p>To get around this explicit routing/dispatching, Comb simply looks for any prepend or append files in each directory leading down to the requested script. In other words, a request for /account/index.php will actually end up running the following scripts in this order, if they exist:</p>
<pre class="brush: bash; highlight: [3]; title: Source Code; notranslate">
/prepend.php
/account/prepend.php
/account/index.php
/account/append.php
/append.php
</pre>
<p>I&#8217;ll refer to this as the <em>execution chain</em>. The prepend and append filenames are also configurable. This enables you to organize your code in such a way that any scripts that require common pre- or post-filtering can simply be placed in the same directory. For example, if the /account directory can only be accessed by authenticated users, your /account/prepend.php script may look like:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
    // assume $user was created in /prepend.php
    if ( !$user-&gt;isLoggedIn ) 
    {
        comb_redirect('/login.php');
    }
</pre>
<p>The comb_redirect() function does three things: </p>
<ol>
<li>Adds a Location: header pointing to the specified URL to the internal headers array</li>
<li>Halts the execution chain, and</li>
<li>turns off rendering.</li>
</ol>
<p>This causes none of the proceeding script in the execution chain to get included, so the comb_run() function will return to the bootstrap script. When comb_render() gets called, it first checks to see if rendering is enabled, but it&#8217;s not anymore thanks to comb_halt(), so it returns to the bootstrap immediately. Then comb_send() is called, which first sends out any user-specified headers (e.g., Location), then checks to see if rendering is enabled. If so it flushes the buffer, but it’s not enabled so comb_send() thus returns and the lifecycle is complete.</p>
<p>That&#8217;s a crash course in what I&#8217;ve got so far. There&#8217;s a bit more that I&#8217;ll cover in my next post, but in the mean time if you&#8217;ve got any feedback on this approach, please let me know. I&#8217;m interested to hear other folks&#8217; opinions on this approach.</p>
]]></content:encoded>
			</item>
		<item>
		<title>Comb Rewrite &#8211; A Quick Overview</title>
		<link>http://drewcking.com/2009/03/comb-rewrite-a-quick-overview/</link>
		<pubDate>Sat, 14 Mar 2009 17:05:22 +0000</pubDate>
		<dc:creator><![CDATA[drew]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Comb]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://drewcking.com/?p=116</guid>
		<description><![CDATA[I&#8217;ve been using Comb, my experimental PHP framework, for a couple of super-secret projects over the past few months (on those sporadic occasions when I actually write code), and it&#8217;s been evolving pretty dramatically. So much so that very little of the original code still exists. I’m still calling it &#8220;Comb&#8221; though, because the underlying [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve been using Comb, my experimental PHP framework, for a couple of super-secret projects over the past few months (on those sporadic occasions when I actually write code), and it&#8217;s been evolving pretty dramatically. So much so that very little of the original code still exists. I’m still calling it &#8220;Comb&#8221; though, because the underlying idea is still the same. It&#8217;s too time consuming to describe the reasons why I changed each part, so suffice it to say the changes are essentially organizational. Instead I&#8217;ll just jump into explaining it from the ground up as it exists now.</p>
<p>To begin with, here’s the now-simplified Apache VirtualHost container that I&#8217;m using:<br />
<span id="more-116"></span></p>
<pre class="brush: bash; highlight: [7,8,9]; title: Source Code; notranslate">
&lt;VirtualHost *:80&gt;
    ServerName      example.com
    DocumentRoot    /vhosts/example.com/www
    ErrorDocument   404 /404.php
 
    &lt;Directory &quot;/vhosts/example.com/www&quot;&gt;
        AllowOverride All
        php_value include_path &quot;.:/vhosts/example.com/www/lib&quot;
        php_value auto_prepend_file /vhosts/example.com/www/comb.php
    &lt;/Directory&gt;
&lt;/VirtualHost&gt;
</pre>
<p>The first four lines should be pretty self-explanatory, but for the rest:</p>
<ol start="7">
<li>Allow the full use of .htaccess files, e.g., for rewrite rules, etc
<li>
<li>Set PHP&#8217;s include_path to the current working dir (when parsing templates), the application&#8217;s lib dir (for app-specific classes), and the system lib dir (for shared classes)</li>
<li>Prepend comb.php in the document root to every requested PHP script.</li>
</ol>
<p>This Apache configuration ensures that every requested script will first run the site&#8217;s comb.php script, which is a very simple, application-agnostic bootstrap script, meaning it&#8217;s basically the same for every app that I build. In fact I could just have one copy of it in a central directory and prepend it from there, but I&#8217;d lose some potential flexibility that way. Though that could probably be coded around. Anyway, here&#8217;s where things get interesting; comb.php looks like this:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
    require '/www/include/load.php';
    spl_autoload_register('load');
 
    $comb = new util_comb();
    $comb-&gt;run();
    $comb-&gt;send();
</pre>
<p>My autoloader is pretty simplistic; it just converts &#8220;util_comb&#8221; into &#8220;util/comb.php&#8221; and tries to include it based on the include_path set in the vhost container.</p>
<p>The util_comb class encapsulates all the crucial routing and response rendering logic. The constructor parses the request URI into its segments and loops over them looking for any files called prepend.php and append.php. If they exist, they&#8217;re added into an array that I refer to as the inclusion list. To visualize this, imagine a request for /user/profile.php?name=drew. The vhost will start by running comb.php, and the following scripts will get added to the inclusion list if they exist:</p>
<pre class="brush: bash; highlight: [3]; title: Source Code; notranslate">
/prepend.php
/user/prepend.php
/user/profile.php
/user/append.php
/append.php
</pre>
<p>in that order. The idea is to sort of mimic the way Apache finds and parses .htaccess files that are (possibly) in each subdirectory.</p>
<p>The next method that&#8217;s called, $comb->run(), simply loops over the inclusion list and include()s each one of them.</p>
<p>Finally, $comb->send() is called, in which the response is created and sent. This is where template rendering or redirecting takes place.</p>
<p>My next few blog entries will go into the details of the inclusion list, how I&#8217;ve set up template rendering, and how to get clean/friendly URLs working.</p>
]]></content:encoded>
			</item>
		<item>
		<title>Pseudo-ENUM in PHP</title>
		<link>http://drewcking.com/2008/08/pseudo-enum-in-php/</link>
		<pubDate>Thu, 14 Aug 2008 06:59:33 +0000</pubDate>
		<dc:creator><![CDATA[drew]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Wishful Thinking]]></category>

		<guid isPermaLink="false">http://drewcking.com/?p=39</guid>
		<description><![CDATA[I&#8217;ve been working on a project lately where I&#8217;m rolling my own basic role-based access control (RBAC) system. In experimenting with different ways to handle the role definitions, I though that it&#8217;d be nice to have a basic enum() function or construct, as a quick, convenient way to define a set of constants. There&#8217;s this [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve been working on a project lately where I&#8217;m rolling my own basic role-based access control (RBAC) system. In experimenting with different ways to handle the role definitions, I though that it&#8217;d be nice to have a basic enum() function or construct, as a quick, convenient way to define a set of constants. There&#8217;s this option:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
    define('ADMIN',     0);
    define('MODERATOR', 1);
    define('EDITOR',    2);
</pre>
<p>but that isn&#8217;t exactly succinct. I&#8217;d rather have something like this:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
    enum('ADMIN', 'MODERATOR', 'EDITOR');
    // ADMIN == 0 
    // MODERATOR == 1 
    // etc.
</pre>
<p><span id="more-39"></span><br />
Of course, that won&#8217;t work. <samp>enum()</samp> doesn&#8217;t exist in PHP. You can kind of mimic the enumerated values with arrays like so:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
    $roles = array(
        'ADMIN'     =&gt; 0,
        'MODERATOR' =&gt; 1,
        'EDITOR'    =&gt; 2,
    );
</pre>
<p>but having to specify those values is tedious. There&#8217;s an easy trick to get around that though:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
    $roles = array(
        'ADMIN',
        'MODERATOR',
        'EDITOR',
    );

    /*
    Array
    (
        [0] =&gt; 'ADMIN'
        [1] =&gt; 'MODERATOR'
        [2] =&gt; 'EDITOR'
    )
    */
 
    $roles = array_flip($roles);
 
    /*
    Array
    (
        [ADMIN]     =&gt; 0
        [EDITOR]    =&gt; 1
        [MODERATOR] =&gt; 2
    )
    */
 
</pre>
<p>Which is cool! But not cool enough, because I want constants, not just array values. Which is cleaner?</p>
<pre class="brush: php; title: Source Code; notranslate">
if ($role == $roles['ADMIN']) // ew  :(
if ($role == ADMIN)           // ahh :)
</pre>
<p>So a bit more digging, and I found that APC can turn an array into a bunch of constants in one fell swoop!</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
    /**
     * Try loading the constants from APC
     */
    if (!apc_load_constants('roles'))
    {
        /**
         * they aren't in APC, so make 'em and define 'em
         */
        $roles = array_flip(array(
            'ADMIN',
            'EDITOR',
            'MODERATOR'
        ));
 
        apc_define_constants('roles', $roles);
    }
 
    /**
     * Now we've got enumerated constants!
     *  ADMIN     == 0
     *  MODERATOR == 1
     *  EDITOR    == 2
     */
</pre>
<p>Obviously you need APC to make this work. One great thing about using <samp>apc_load_constants()</samp> is that you might get a modest speed boost because you don’t have to <samp>define()</samp> all of your constants every time the script runs. Another benefit is that you can load up your array of roles (or whatever your constants are, e.g., permissions, etc.) from a database or other dynamic source, and convert them into global constants with one function call.</p>
<p>Now what would be even cooler is if you could tell <samp>apc_load_constants()</samp> to load the constants into a specific namespace, maybe something like:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
    apc_load_constants('roles', true, 'drew');
 
    echo &quot;ADMIN's value: &quot; . drew::ADMIN;
</pre>
<p>How cool would that be? Though that kind of namespace madness will need to wait until PHP 5.3 I assume.</p>
]]></content:encoded>
			</item>
		<item>
		<title>Clean URLs &#8211; Basic mod_rewrite rules</title>
		<link>http://drewcking.com/2008/07/clean-urls-basic-mod_rewrite-rules/</link>
		<pubDate>Thu, 03 Jul 2008 13:14:49 +0000</pubDate>
		<dc:creator><![CDATA[drew]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Apache]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://drewcking.com/?p=63</guid>
		<description><![CDATA[I&#8217;ve been using Comb with a few more projects recently. The main point of Comb is to structure the code in such a way that the request handlers get accessed directly via Apache, as opposed to rewriting the entire URL, and making PHP dynamically include or instantiate a request handling class (i.e. Action, Command, etc). [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve been using Comb with a few more projects recently. The main point of Comb is to structure the code in such a way that the request handlers get accessed directly via Apache, as opposed to rewriting the entire URL, and making PHP dynamically include or instantiate a request handling class (i.e. Action, Command, etc).</p>
<p>For example, you might have a registration form that is accessed like this (pseudo-HTTP):</p>
<pre class="brush: bash; title: Source Code; notranslate">
# display the registration page...
GET  /register.php
 
# registration form submits to...
POST /proc_register.php
</pre>
<p>I personally hate that naming convention because it reminds me of how I wrote code 5 years ago, and it&#8217;s just plain ugly.</p>
<p>Here&#8217;s a cleaner, friendlier approach that I&#8217;d rather use:<br />
<span id="more-63"></span></p>
<pre class="brush: bash; title: Source Code; notranslate">
# display the registration page...
GET  /register
 
# registration form submits to...
POST /register
</pre>
<p>Yep, that&#8217;s a postback. And yep, there&#8217;s no .php extension used to access it, so some URL rewriting will be in order. I&#8217;ll add the following code into my virtualhost container in the Apache config:</p>
<pre class="brush: bash; title: Source Code; notranslate">
# turn on the voodoo
RewriteEngine On
 
# if the incoming request has one of these extensions, 
# just serve up the file without rewriting anything
RewriteRule     /*\.(php|html|css|js|jpe?g)$ - [NC,L]
 
# just a little shortcut to make it easier to deal with 
# case-sensitivity
RewriteMap      lc      int:tolower
 
# make clean/friendly URLs work
# e.g., turn this:  GET /register
#       into this:  GET /register_get.php
# 
# and turn this:   POST /register
#     into this:   POST /register_post.php
#
RewriteRule  /(.*)  /$1_${lc:%{REQUEST_METHOD}}.php [NC,QSA,L]
</pre>
<p>After restarting Apache, I&#8217;ll create these two files to make sure the rewrite is working properly:</p>
<p>register_get.php</p>
<pre class="brush: xml; highlight: [4]; title: Source Code; notranslate">
&lt;html&gt;
&lt;body&gt;
 
  &lt;form method=&quot;post&quot;&gt;
    Username: &lt;input type=&quot;text&quot; name=&quot;username&quot; /&gt;&lt;br /&gt;
    &lt;input type=&quot;submit&quot; /&gt;
  &lt;/form&gt;
 
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Note the form tag on line #4, it&#8217;s simply <samp><br />
<form method="post"></samp> without the expected <samp>action=&#8221;/register&#8221;</samp> attribute. By leaving the action attribute absent or blank, the browser will simply submit the form back to the current address, i.e., a post-back.</p>
<p>Luckily our rewrite rule will see that the incoming request is a POST instead of a GET, so it&#8217;ll route the request into a different script:</p>
<p>register_post.php</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
    echo &quot;posting registration form...&quot;;
    var_dump($_POST);
</pre>
<p>Nothing magical happening in there, but the point is that mod_rewrite can be used to run different scripts based on the <samp>%{REQUEST_METHOD}</samp> variable, so you can organize the scripts according to the action being performed. It would even route PUT, HEAD, and DELETE requests to <samp>/register_put.php</samp>, <samp>/register_head.php</samp>, and <samp>/register_delete.php</samp>, respectively. Assuming the HTTP client was capable of sending those requests (e.g., AJAX).</p>
]]></content:encoded>
			</item>
		<item>
		<title>Pagination with MySQL and FOUND_ROWS()</title>
		<link>http://drewcking.com/2008/07/pagination-with-mysql-and-found_rows/</link>
		<pubDate>Tue, 01 Jul 2008 04:15:37 +0000</pubDate>
		<dc:creator><![CDATA[drew]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://drewcking.com/?p=188</guid>
		<description><![CDATA[Jody clued me into a convenient method of paginating a result set from MySQL. Since he hasn&#8217;t blogged about it yet, I will >:-) In the past, I&#8217;d issue two queries back to back, similar to this: Take note of Line #8. The first query grabs the specified page of results, the second simply does [&#8230;]]]></description>
				<content:encoded><![CDATA[<p><a href="http://www.jodymickey.com" target="_blank">Jody</a> clued me into a convenient method of paginating a result set from MySQL. Since he hasn&#8217;t blogged about it yet, I will >:-)</p>
<p>In the past, I&#8217;d issue two queries back to back, similar to this:<br />
<span id="more-188"></span></p>
<pre class="brush: php; highlight: [8,9]; title: Source Code; notranslate">
&lt;?php
    $page = isset($_GET['page']) ? (int) $_GET['page']: 1;
    $size = 10;
    $offset = ($page - 1) * $size;
 
    $db = new mysqli(&quot;localhost&quot;, &quot;drew&quot;, &quot;mypass&quot;, &quot;db&quot;);
 
    $sql = &quot;SELECT username FROM user LIMIT $offset, $size;&quot;
         . &quot;SELECT COUNT(*) FROM user&quot;;
 
    $users = array();
    $total = 0;
 
    if ($db-&gt;multi_query($sql) &amp;&amp; $res = $db-&gt;store_result())
    {
        // fetch this page of user records
        while (list($name) = $res-&gt;fetch_row())
        {
            $users[] = $name;
        }
 
        // fetch the TOTAL number of users
        $db-&gt;next_result();
        list($total) = $db-&gt;store_result()-&gt;fetch_row();
    }
 
    $pages = ceil($total/$size);
 
    echo &quot;Total Users: $total&lt;br&gt;&quot;;
    echo &quot;Total Pages: $pages&lt;br&gt;&quot;;
    echo &quot;Current Page: $page&lt;br&gt;&lt;br&gt;&quot;;
 
    foreach ($users as $u) echo &quot;$u&lt;br&gt;&quot;;
 
    if ($page &gt; 1) 
        echo '&lt;a href=&quot;?page=', $page-1, '&quot;&gt;&amp;laquo; Prev&lt;/a&gt;';
 
    if ($page &gt; 1 &amp;&amp; $page &lt; $pages) 
        echo &quot; | &quot;;
 
    if ($page &lt; $pages) 
        echo '&lt;a href=&quot;?page=', $page+1, '&quot;&gt;Next &amp;raquo;&lt;/a&gt;';
</pre>
<p>Take note of Line #8. The first query grabs the specified page of results, the second simply does a full count of all rows so I could calculate the total number of pages.</p>
<p>What sucks, however, is if the query is more complex, especially if the various parts of it have to be dynamically generated, e.g., table joins, conditions in the where clause, etc. In such a case you’d have to change the second query to get rid of the column list SELECT column1, column 2&#8230; and make it SELECT COUNT(*). Also, you’d have to toss out any ORDER BY and LIMIT clauses.</p>
<p>MySQL allows you to simplify this extremely common scenario by using the <a href="http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows" target="_blank">FOUND_ROWS()</a> function. In the above code, you can simply modify the query itself:</p>
<pre class="brush: php; title: Source Code; notranslate">
&lt;?php
    // ... change this:
    $sql = &quot;SELECT username FROM user LIMIT $offset, $size;&quot;
         . &quot;SELECT COUNT(*) FROM user&quot;;
 
    // ... to this:
    $sql = &quot;SELECT SQL_CALC_FOUND_ROWS username FROM user LIMIT $offset, $size;&quot;
         . &quot;SELECT FOUND_ROWS()&quot;;
</pre>
<p>The rest of the code remains the same and will give you the exact same results.</p>
<p>The speed of this approach can vary depending on how you have your table(s) indexed, and the complexity of the query itself. In other words, in some circumstances it may be faster to actually run the LIMITed query followed by the appropriate <samp>SELECT COUNT(*) FROM &#8230;</samp> query as in the first example, but the primary benefit is in the simplification of the query itself.</p>
]]></content:encoded>
			</item>
		<item>
		<title>Comb: auto_prepend_file, output buffering, and mod_rewrite</title>
		<link>http://drewcking.com/2008/05/comb-auto_prepend_file-output-buffering-and-mod_rewrite/</link>
		<pubDate>Fri, 09 May 2008 17:11:12 +0000</pubDate>
		<dc:creator><![CDATA[drew]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Apache]]></category>
		<category><![CDATA[Comb]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://drewcking.com/?p=184</guid>
		<description><![CDATA[I&#8217;ve decided to give a name to this barebones framework that I&#8217;ve been playing with for the past couple of months. I&#8217;m calling it Comb. Unfortunately it takes a long time to fully explain the thinking behind the name. Similar to Camber, however, the jist of it is simplicity; think &#8220;get the tangles out of [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve decided to give a name to this barebones framework that I&#8217;ve been playing with for the past couple of months. I&#8217;m calling it Comb. Unfortunately it takes a long time to fully explain the thinking behind the name. Similar to Camber, however, the jist of it is simplicity; think &#8220;get the tangles out of my code&#8221;. Plus comb is a lot faster to say and type than MVCish-framework-based-on-autoprependfile-and-output-buffering.</p>
<p>My plan is to build the simplest web app framework that I can. I&#8217;m by no means an expert, and I don&#8217;t anticipate that this will end up being the best/fastest/most-convenient framework that will lay waste to the <a href="http://framework.zend.com/" target="_blank">Zend Framework</a>, or <a href="http://symfony.com/" target="_blank">Symfony</a>, or <a href="http://kohanaframework.org/" target="_blank">Kohana </a> (or the mystical Redline! no link, it’s too mystical!). I just want to start from the ground-up by making very few assumptions, and without ripping &#8220;inspiration&#8221; from the latest and greatest RAD framework. I want to end up with a simple base of code that I don&#8217;t have to learn how to love, and that can evolve with me without getting in the way. Basically this is all about me, but you can feel free to use it as well if it makes enough sense.</p>
<p>I&#8217;ve got a few projects in mind that I&#8217;m planning on being powered by Comb. The first is my Code Examples site, which will serve two purposes: it&#8217;ll be a place to host demos of basic code for the blog entries I write, and it&#8217;ll be a testbed for integrating new features into the framework. And yes, the code that runs the examples site is Comb itself. The other projects will be revealed in time.</p>
]]></content:encoded>
			</item>
	</channel>
</rss>
