<?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>Ralph Schindler &#187; Best Practices</title>
	<atom:link href="http://ralphschindler.com/tag/best-practices/feed" rel="self" type="application/rss+xml" />
	<link>http://ralphschindler.com</link>
	<description>Ralph Schindler</description>
	<lastBuildDate>Mon, 19 Sep 2011 21:38:12 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Autoloading (Revisited)</title>
		<link>http://ralphschindler.com/2011/09/19/autoloading-revisited</link>
		<comments>http://ralphschindler.com/2011/09/19/autoloading-revisited#comments</comments>
		<pubDate>Mon, 19 Sep 2011 20:43:16 +0000</pubDate>
		<dc:creator>Ralph Schindler</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Software Architecture]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://ralphschindler.com/?p=154</guid>
		<description><![CDATA[Upon the arrival of PHP 5.0, the ability to autoload classes was introduced. At the time, autoloading was such a new feature, it was hardly adopted. As such, many applications being ported from PHP4 to PHP5 still had lots of procedural code in them (code incapable of being be autoloaded) and many class files which [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop --><!-- End Shareaholic LikeButtonSetTop --><p>Upon the arrival of PHP 5.0, the ability to autoload classes was introduced. At the time, autoloading was such a new feature, it was hardly adopted. As such, many applications being ported from PHP4 to PHP5 still had lots of procedural code in them (code incapable of being be autoloaded) and many class files which had long &#8216;<tt>require_once</tt>&#8216; lists. It wasn&#8217;t until years later that certain best practices had emerged and the prolific usage of <tt>require_once/include_once</tt> throughout large bodies of code had started drying up. Even after autoloading had been adopted by larger more visible projects, a common patten had yet to emerge.  The PEAR project had already had its one-class-per-file rule, and a class to filesystem naming convention, but this was hardly the rule at the time, and as such, there were many different patterns of autoloading strategies.</p>
<p>As time has passed, slowly, more and more projects had gone through re-writes and the strategy that most projects were landing on was the one that came from the PEAR group. Fast-forward to today, and we see that this standard for autoloading has agreed upon by a large number of projects and has come to be named the &#8220;PSR-0 autoloading standard&#8221;.</p>
<h2>What We&#8217;ve Learned</h2>
<p>After having attained a consistency (for code) in how we utilize autoloading, we&#8217;ve attempted to find the most efficient and performance optimized way of executing our autoloading strategy. Matthew Weier O&#8217;Phinney <a href="http://weierophinney.net/matthew/archives/245-Autoloading-Benchmarks.html">has blogged</a> about this in the past, it&#8217;s a good read if you have not already read it. To summarize, he found the following things to be true:</p>
<ul>
<li>disk based class name to filesystem location maps are the fastest lookups</li>
<li>class filesystem paths that are absolute and that do not rely on include_path are fastest</li>
<li>lightweight autoload functions that utilize class maps directly are the fastest</li>
</ul>
<p>For more information about the above generalization, see Matthew&#8217;s blog post.</p>
<p>Nearly a year ago, in conjunction with his findings, Matthew also wrote a classmap generation <a href="https://github.com/weierophinney/zf2/blob/master/bin/classmap_generator.php">tool</a>. This tool produced a <tt>.classmap.php</tt> file that would reside in the directory responsible for containing class files. The general idea here is that a developer could utilize a automatic mapping based autoloader, like the PSR-0 autoloader, or, he could utilize this <tt>.classmap.php</tt> file in order to build a more performance centric strategy for his/her autoloading needs.</p>
<p>This approach presents developers with two primary problems. One, dot files are generally hidden on a filesystem, and as such, this means that this PHP data array is also part of a code-path that is hidden from most developers view of the codebase. This then lead to moments of confusion when something related to the location of classes goes awry. The second of the problems it that this strategy assumes that the consumer has some way of consuming the contents of this class-map file. For ZF users, they could utilize one of the shipped <tt>Zend\Loader</tt> classes that are designed to use a class-map. The problem here is not necessarily for ZF users, but that it is promoting a strategy that is more ZF specific than generic in nature.</p>
<p>The addition of, and swift adoption of PHP&#8217;s namespace support in PHP 5.3 has also presented us with both a platform for standardization as well as a few challenges. Traditionally, when we thought of the PEAR naming convention, we assumed that for a given class (in prefix notation) <tt>Alpha_Beta_Gamma</tt>, there would be a single mapping of this class to a single place on the filesystem, namely: <tt>some/path/Alpha/Beta/Gamma.php</tt>. This inherently presents no problems. What does present a problem is if we have another project that utilizes part of this prefix, but in a different location. Assume that you want to use part of the prefix, for example, the Alpha_Beta_ portion, with a different logical component/module/project within your organization. In this case, it might make sense that class <tt>Alpha_Beta_Gamma</tt> live in one project on disk, and that <tt>Alpha_Beta_Omega</tt> live somewhere completely different. Any number of situations could realistically present this problem, but the most apparent is that your organization wants to utilize a naming scheme that allows for <tt>MyCompany_MyDivisionWithinMyCompany_PerhapsSomeLogicalComponent_ClassName</tt>.</p>
<p>In any of the likely scenarios of the above, a simple mapping rule that might govern one class name to filesystem name autoloader will not work for another class that could conceivably within the same project without some kind of either autoloader filter, or filesystem munging. Either way, we can no longer make the assumption that a simple map of class name to one location on disk mapping will suffice.</p>
<p>More an more, we are seeing this pattern emerge, (this time with namespace):</p>
<pre class="brush: php; title: ; notranslate">
namespace VendorName\ComponentName {

    class SomeComponentClass {

    }

}
</pre>
<p>This class is then found inside its own logical project, with its own data files, web files, or test files in a project structure that looks similar to this:</p>
<pre class="brush: bash; title: ; notranslate">
path/to/VendorName_Component/
    src/
        VendorName/
            ComponentName/
                SomeComponentClass.php
    data/
        some-data-file.txt
    tests/
        phpunit.xml
        phpunit-bootstrap.php
        VendorName/
            ComponentName/
                SomeComponentClassTest.php'
    docs/
        some-documentation-format.xml
    README.md
</pre>
<p>As you can imagine, any one vendor/organization who&#8217;s in the business of building software will more than likely have more than one project that both utilizes this kind of naming scheme and also takes advantage of this listed project structure for developing and releasing this bit of code. This being the case, unless the project is merged with other code for the purposes of a consuming project, parts of the namespace will exist in two separate parts of the filesystem &#8230; something which, a specialized autoloader will need to take into consideration.</p>
<p>Ideally, we should find a solution that will present class-map based autoloading in a way that is an easily identifiable code pattern, simple, expressive, works well with common development practices and takes advantages of the current day PHP platform (namespaces and autoloading facilities).</p>
<h2>And, What I&#8217;ve Found Is This &#8230;</h2>
<p>And, what I&#8217;ve found is that projects should present a few different options as per how they provide an &#8220;out-of-the-box&#8221; experience as it relates to autoloading. Such a solution should offer the consumer a usage story that consists of the most minimal of requirements when it comes to bootstrapping this 3rd party code. Let&#8217;s examine the following project structure (expanded from our example above):</p>
<pre class="brush: bash; title: ; notranslate">
path/to/VendorName_Component/
    src/
        VendorName/
            ComponentName/
                SomeComponentClass.php
    data/
        some-data-file.txt
    tests/
        phpunit.xml
        phpunit-bootstrap.php
        VendorName/
            ComponentName/
                SomeComponentClassTest.php'
    docs/
        some-documentation-format.xml
    autoload_classmap.php
    autoload_function.php
    autoload_register.php
    README.md
</pre>
<p>What you&#8217;ll notice is the addition of 3 <tt>autoload_*.php</tt> files. Let&#8217;s have a look at what these files provide and the reasons for their existence. First the <tt>autoload_classmap.php:</tt></p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
return array(
    'VendorName\Component\SomeComponentClass' =&gt; __DIR__ . '/src/VendorName/ComponentName/SomeComponentClass.php'
    /* .. other classes here .. */
);
</pre>
<p>This file provides the exact map of the classname to the location on disk that this class can be found in. This file takes advantage of PHP&#8217;s ability to have return values returned from the inclusion of a file. A simple usage story for this file might be:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
// ...
$classmapAutoloader = new MyClassMapAutoloader();
$classmapAutoloader-&gt;loadClassMap(include __DIR__ . '/vendors/VendorName_Component-1.5/autoload_classmap.php');
// ...
</pre>
<p>Let&#8217;s next look at the <tt>autoload_function.php</tt> file:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
return function ($class) {
    static $classmap = null;
    if ($classmap === null) {
        $classmap = include __DIR__ . '/autoload_classmap.php';
    }
    if (!isset($classmap[$class])) {
        return false;
    }
    return include_once $classmap[$class];
};
</pre>
<p>This file provides a closure based autoloader as its return value. This function can then be used by the consumer directly for injecting into their own autoloader stack/queue, or directly into the autoloader queue provided by PHP:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
// ...
spl_autoload_register(include __DIR__ . '/vendors/VendorName_Component-1.5/autoload_function.php');
// ... or ...
$autoloader = new MyFancyAutoloader();
$autoloader&gt;registerAutoloaderFunction(include __DIR__ . '/vendors/VendorName_Component-1.5/autoload_classmap.php');
</pre>
<p>Either way, the consumer is provided with a callback that is capable of being utilized, in a single line, to bootstrap this components autoloading needs.</p>
<p>Finally, the complete, one line solution can be found by utilizing <tt>autoload_regsiter.php</tt> directly:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
// autoload_register.php
spl_autoload_register(include __DIR__ . '/autoload_function.php');
</pre>
<p>While the above is so trivial as to ask why it should be included, it does offer a single-line usage story:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
// ...
require_once __DIR__ . '/vendors/VendorName_Component-1.5/autoload_register.php';
</pre>
<p>Why not do this in the first place? Well, this approach is assuming the consumer does not necessarily care about how the autoload function is loaded into PHP&#8217;s <tt>spl_autoload</tt> queue. One thing to keep in mind is that when <tt>spl_autoload_register()</tt> is called, autoloaders are placed as the end of the queue by default. This behavior can be changed by passing true as the 3rd parameter of <tt>spl_autoload_register()</tt>. This type of performance optimization might be important when you know some autoload-able code will be utilized more often than other code, and thus you want the autoloader for that code to be consulted first. Another reason for this kind of user registration is that some autoloaders might be so generic as to want to act as a fallback autoloader or a generic autoloader. For these kind of autoloaders, it is important that they always be last in the queue since they might throw an error or exception when they cannot find a class as opposed to returning false and letting other autoloader have an attempt at finding the class requested.</p>
<h2>Conclusion</h2>
<p>The above mentioned strategy is something to be considered if you are creating reusable PHP components that you wish provide perhaps as Pyrus packages and/or as PHP phar archives for 3rd party consumption. This autoloading strategy provides an out-of-the-box usability experience in minimal amount of code. It also plays nice with other autoloaders, provides a solution that is opcode cacheable, and since it utilizes absolute paths (via <tt>__DIR__</tt>) &#8211; minimizes the amount of stat() calls to the filesystem your application will generate during its runtime.</p>
<div class="shr-publisher-154"></div><!-- Start Shareaholic LikeButtonSetBottom --><!-- End Shareaholic LikeButtonSetBottom -->]]></content:encoded>
			<wfw:commentRss>http://ralphschindler.com/2011/09/19/autoloading-revisited/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Learning About Dependency Injection and PHP</title>
		<link>http://ralphschindler.com/2011/05/18/learning-about-dependency-injection-and-php</link>
		<comments>http://ralphschindler.com/2011/05/18/learning-about-dependency-injection-and-php#comments</comments>
		<pubDate>Wed, 18 May 2011 20:25:09 +0000</pubDate>
		<dc:creator>Ralph Schindler</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Software Architecture]]></category>
		<category><![CDATA[Software Engineering]]></category>

		<guid isPermaLink="false">http://ralphschindler.com/?p=144</guid>
		<description><![CDATA[Over the past few years, there are a few concepts and programming patterns that have muscled their way into the hearts and minds of PHP developers from other languages and programming communities. These concepts range from the MVC application architecture as well as various modeling techniques (think ActiveRecord and Data Mapper), to a pure shift [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop --><!-- End Shareaholic LikeButtonSetTop --><p>Over the past few years, there are a few concepts and programming patterns that have muscled their way into the hearts and minds of PHP developers from other languages and programming communities.  These concepts range from the MVC application architecture as well as various modeling techniques (think ActiveRecord and Data Mapper), to a pure shift in the way we think about application architectures, like aspect-oriented programming (AoP) and event-driven programming.  Perhaps it&#8217;s because PHP has been adopted at an enterprise level thus increasing the demand for what developers might call <i>enterprise quality programming patterns</i>, or perhaps it&#8217;s simply because of PHP&#8217;s ever evolving object model that makes new things possible.  After all, who doesn&#8217;t like new shiny things?  Whatever the reason, one of the newest concepts (at least over the past 3 years or so) that has emerged as one of our heated topics of debate is <em>how to manage object dependencies</em>.  Interestingly, the argument of how to manage dependencies is generally named by the solution which its proponents give as <strong>the solution</strong>: <em><a href="http://en.wikipedia.org/wiki/Dependency_injection">dependency injection</a></em> (the abstract principle is actually called <a href="http://en.wikipedia.org/wiki/Inversion_of_control">Inversion of control</a>).</p>
<p>In any circle of developers that are of the object-oriented persuasion, you&#8217;ll never hear an argument that dependency injection itself, is bad.  In these circles, it is generally accepted that injecting dependencies is the best way to go.  Injecting object dependencies in PHP looks like this:</p>
<pre class="brush: php; title: ; notranslate">

// construction injection
$dependency = new MyRequiredDependency;
$consumer = new ThingThatRequiresMyDependency($dependency);
</pre>
<p>That&#8217;s basically it.  There are many variations of this: setter injection, interface injection, call time injection, in addition to the above mentioned constructor injection. These are all valid ways of injecting the dependencies into the consuming object.  Ultimately, the goal here is to avoid this:</p>
<pre class="brush: php; title: ; notranslate">

class ThingThatHasAnExternalDependency
{
    public function __construct() {
        $this-&gt;dependency = new ARequiredDependency;
        // or
        $this-&gt;secondDependency = ARequiredDependency::getInstance();
    }
}
</pre>
<p>The above code is an example of a violation of the <a href="http://en.wikipedia.org/wiki/Hollywood_Principle">Hollywood Principle</a>, which basically states: &#8220;Don&#8217;t call us, we&#8217;ll call you.&#8221;.</p>
<p>Yet, this is not the heart of the argument.  Perhaps it was 4-5 years ago in the PHP community, but it&#8217;s not anymore.  The heart of the argument is not should we be doing it, but <em>how do we go about doing it</em>.  </p>
<p>This article is not about the intricacies and implementation details of DI containers and DI frameworks.  It&#8217;s also not about the various ways and means of injecting dependencies into other objects, or which method might be better.  In fact, this article has no opinion if injecting dependencies is even good for you or your application.  This article is an exploration how adopting any DI framework for PHP affects the lifecycle of a project, both the code as well as the developer, team or organization that is constructing it.</p>
<h3>A Brief History of Dependency Management In PHP</h3>
<p>It is important to know why PHP is as popular as it is, after all, it&#8217;s this popularity that DI Frameworks fight against for adoption inside a PHP application framework.  To understand PHP&#8217;s popularity, history, and evolution, let&#8217;s look at this code:</p>
<pre class="brush: php; title: ; notranslate">
// these 6 lines actually represent 5 different web centric &quot;langauges&quot;!
include_once 'includes/config.php'; // ultimately there is a mysql_connect() call in here somewhere
include_once 'templates/header.php';
$rows = mysql_query('SELECT * FROM users'); // magically uses the mysql_connect() resource
foreach ($rows as $row) {
    echo '&lt;div class=&quot;user-row&quot;&gt;&lt;a href=&quot;/delete-user.php&quot; onclick=&quot;someJSFunction();&quot;&gt;' . $row['username'] . '&lt;/div&gt;';
}
include_once 'templates/footer.php';
</pre>
<p>From the beginning, we&#8217;ve been trained into thinking that our dependencies are magically managed.  As you can see above, the mysql_query() function, while it will accept a connection resource, does not require it.  In fact, if it&#8217;s not supplied, it will use the first open mysql connection it can find inside the PHP runtime.  Assuming that the above mentioned delete-user.php script is part of a larger collection of PHP scripts, which we will call &#8220;the application&#8221; &#8230; it is important to note that even this script itself is pulling in its dependencies instead of them being injected.  For all intents and purposes, the config.php, header.php and footer.php are all dependencies of this script, much like other scripts similar in nature to this delete-user.php.  To sum it up, if there is a new dependency that is now required by the business logic portion of this application (ie: the lines between the header and footer), they now have to be introduced to <em>all scripts</em> in this application.  This does not exactly adhere to the <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a> principle.</p>
<p>But, let&#8217;s take a step back and look at this snippet of code from the organizational perspective.  To do this, we must first understand the various phases of the code&#8217;s lifecycle within any organization.  For the purposes of this example, let&#8217;s assume that from idea to production, code will go through the following phases: development, build, deployment, to application start-up (in production).  If this were a C/C++ or Java project, code will have been written (developed), it will have been compiled (built), then it would have been packaged or some deployment tool&#8217;s process invoked (deployed); it them would have been run (executed via some startup script, or executing a binary.)  PHP, and Perl at the time, achieved all of the same objectives but in fewer steps making it a wildly popular platform for highly iterative web projects.  This same application in PHP would have been coded in some text editor (developed), and FTP&#8217;d up to a production server (deployed).  You&#8217;ll notice that it neither had to be built/compiled, or started on the server since the target, Apache, was already running with PHP embedded into it.  For all intents and purposes, a cheap and easy FTP tool was both the build and deployment tool for this application&#8217;s lifecycle.</p>
<p>It was this simplicity that made PHP the popular choice for web applications.  This popularity was attained because the simplicity of the PHP platform allowed for two extremely important facets of development to emerge: the idea of building an application became approachable to even the novice individual, and without all the cruft that came along with the application lifecycle, building and deploying applications in PHP increased PHP&#8217;s &#8220;fun-ness&#8221; factor.</p>
<p>While this style of building applications allowed for a proliferation of PHP applications to be developed, there was in fact a negative side to be revealed later in time.  As applications quickly grew, their ability to be maintained decreased.  We give them the name <a href="http://en.wikipedia.org/wiki/Spaghetti_code">&#8220;Spaghetti code&#8221;</a>, and for all the right reasons.  Objects, if they were even being used, were generally wrappers around procedural functionality.  So object dependency management wasn&#8217;t even a consideration for most developers.  Looking back, perhaps it was this original simplicity that allowed developers to create applications without even having to know what a dependency was or how to find it.  In any case, as these applications grew uncontrollably, maintaining them and hacking them started to lose the PHP fun factor exponentially.</p>
<h3>A Brief History of DI Frameworks</h3>
<p>As PHP developers started identifying the problems with their <a href="http://en.wikipedia.org/wiki/Model_1">Model 1</a> applications, they started looking for solutions in other programming communities.  At this time, the Java community was still heavily rooted in the enterprise/software development/software engineering world, and problems such as dependency management already had some interesting solutions.  Most notably, there was the <a href="http://en.wikipedia.org/wiki/Spring_Framework">Spring Framework</a>, who&#8217;s primary facility for dependency management was a component called the IoC Container, or the Inversion of Control container.  This container managed the fully lifecycle of object creation using callbacks.  This meant that you no longer has to use the &#8220;new&#8221; keyword (the same new keyword in PHP).  Also, it wired the dependencies for you at instantiation time.  This meant that you no longer had to concern yourself with how dependencies were injection; be it through the constructor, properties or setter methods.  The Spring Framework was one of the first frameworks that encouraged the use of definition files to manage the knowledge required to wire all your dependencies together.  True to form in the Java community, these definition files were created in XML.</p>
<p>As it might seem, this is indeed a deviation from the PHP philosophy that had made PHP so popular.  PHP allowed you to write the most minimal amount of code to complete your application.  In the Java/DI world, particularly with the Spring framework, you had a much richer application lifecycle.  Not only were you developing code for your appliation, but you were creating code about code to manage code.  This is known as <a href="http://en.wikipedia.org/wiki/Meta-programming">meta-programming</a>.  In addition to this meta-programming that was going on, you also now had this compilation phase required by the Java platform which was generally tucked away inside your build time tasks.  Moreover, this application had to be deployed (there were generally tools for this too), and (for good measure), due to the platform, your application had to be started.  Needless to say, this application lifecycle might seem <em>heavier</em>, for lack of a better term, to the average PHP developer.</p>
<p>Since then, several frameworks have cropped up that sport some kind of dependency management.  Before this technique was picked up in PHP, they were all heavily rooted in the Java and .NET communities.  A quick google search will return a few notable names like PicoContainer, Spring.NET, Unity, Butterfly and google-guice to name a few.  These frameworks attain popularity since they attempt to ease some of the burdens that DI places upon the developer whether it be by using reflection to create definitions, or even adding an annotation system so that DI definitions can be written inside the code they are set to manage.</p>
<h3>DI and PHP</h3>
<p>To understand the attainability of having a dependency management framework for PHP, one should first understand how the counterparts in Java and .NET rely upon their respective platforms to do certain jobs.  For a quick reference, see the images from this <a href="http://ralphschindler.com/2010/05/06/phpundamentals-series-a-background-on-statics-part-1-on-statics">blog post</a>.  One of the more important facets to remember is that the expected application lifecycle of a Java/.NET application is much richer.  You are expected to have build-time tasks.  You are expected to have deployment tasks.  And, generally, your application understand the difference between being in development, staging and production &#8211; so it can adjust how it runs accordingly.  Moreover, the platform itself has facilities in place that aid the developer both in development time with code generation as well as in production.</p>
<p>PHP never expects or facilitates the usage of any kind of build-time tasks.  PHP also does not have any kind of built-in annotation support (a meta-programming technique), nor does it have any kind of application scope or per-application memory space.  What does this mean for someone who is creating a DI container? Let&#8217;s explore.</p>
<h4>Development Time</h4>
<p>General speaking, any time you are writing, altering or just shifting code around, you are in development mode, your application should be running in a development environment.  The structure of your application&#8217;s classes, functions and files within the filesystem is probably changing with each time you click save.  Dependency management systems require knowledge of your code in order to effectively do their job.  This knowledge generally comes in the form of some kind of definition.</p>
<p>This definition can be created by hand, by the developer, generated at runtime by some application hooks, or generated with the use of a special tool.  If this is done by hand, a developer is required to explicitly map the various functions/methods that will need to be called in order to inject a particular object dependency.  The more dependencies you have, the more verbose this definition might become.</p>
<p>A better route would be to generate this definition file, after all, the code you&#8217;ve written, if written correctly will self-describe its dependencies.  There are two options for generation, manual and automatic.  An example of manual generation would be a developer giving a command line tool the minimal information it needs to be able to go parse your code, figure out the dependency map for itself, and generate some kind of definition to be used during runtime.  Minimal information might include some kind of seed information like where to find your classes or perhaps what filters to use when inspecting classes.  Sometimes, these tools might make use of special interfaces (also called interface injection) to understand that their purpose is to describe the various dependencies of the class implementing said interface.  Another approach might be to utilize special annotations on classes and class methods that describe the various required and optional dependencies and how they are to be injected.</p>
<p>The same techniques employed in this manual approach could also be put to use in an automatic approach.  In automatic approach, imagine this same command line tool from the manual approach was now a service of the application itself.  While in development mode, it would run as often as need be in order to determine if code changes have happened.  If they have, the service would regenerate the dependency definition file so that the rest of the application can utilize the dependency definition inside the DI container available to the application during runtime.</p>
<p>There are a couple of concerns that are specific to PHP with regards to dependency management.  Since PHP is a share-nothing architecture with no application level memory, this definition would need to be loaded and parsed and put into memory on each request.  The larger the dependency tree that you track, the larger the memory footprint of the dependency definition graph.  Furthermore, since this definition has to be loaded on each request, if it is in a non-native format (meaning anything other than PHP code), there are certain costs with converting this format, be it XML, YAML, JSON, or INI to the in-memory structure that the dependency management container requires.  What&#8217;s more, the PHP platform does not keep track of file changes.  So without some kind of user-land tracking, it is hard to know what files during development have changed.  Thus, your dependency management system, if it&#8217;s taking an automatic approach, would have to rescan the filesystem for changes upon each request during development &#8211; which has its own consequences.</p>
<h4>Deployment Time</h4>
<p>When one is done writing code and is ready to push this application into production, the act of pushing this application is called deployment.  The mode for this application is now considered &#8220;production&#8221;.  In production, you can be sure that the structure of your code is stable and will not change, thus your dependency graph is now safe from changes too.  Since this is the case, there is no longer a need to keep updating and regenerating this dependency definition file like you were during development.</p>
<p>Even though the definition is no longer changing, there still is the concern about how expensive it is to load this definition each request.  Naturally, the cheapest form of definition would be a PHP array or structure describing the definition that can then be loaded in-memory.  Other file types like XML, YAML, JSON, etc first have to go through a parsing phase before they can be used.  This activity of parsing these files could be expensive, and could benefit from some kind of caching.  Caching the definition in some way shape or form, would ensure there is minimal overhead per-request when the application is using this dependency management container.</p>
<h3>Other Observations &amp; Criticisms</h3>
<p>It is important to realize that dependency management solutions in and of themselves are, in all the available words, full frameworks.  They require that you understand both their philosophy as well have a minimal understanding of what facilities they are offering in order to use them effectively.  To understand the true benefits of any framework one must first know the pain points the framework is attempting to solve.  Seeing the end result of a framework without knowing what it is facilitating might lead to one to dismiss it as overkill or unintuitive.  For example, take the following code (typical of dependency management systems)</p>
<pre class="brush: php; title: ; notranslate">
$userRepository = $dic-&gt;get('UserRepository');
</pre>
<p>If you encounter this line of code without fully understanding the dependency injection container being used, you wouldn&#8217;t be able to appreciate its usefulness.  You could instantiate your Application\Model\UserRepository yourself, sure, but you&#8217;d also have to locate and inject the database adapter to use and into that you&#8217;d have to inject and load the configuration for that database connection.  If you are doing this in multiple controller actions, there is a lot of repeated boilerplate code that is required to &#8220;wire&#8221; the UserRepository object.  Internally, the DiC object is loading and consulting a definition, creating objects, injecting those objects, and returning the requested object that has been fully wired and ready to use.</p>
<p>The above code also demonstrates two common criticism of dependency management frameworks, which is also a criticism of frameworks in general.  By using this framework, you are moving further away from the facilities of the language or platform itself.  Instead of using the &#8220;new&#8221; keyword to create a new object, you&#8217;ve asked another object to create this requested object for you.  What this has done has shifted developers away from utilizing the language&#8217;s well understood API and onto the framework&#8217;s API.  Additionally, this kind of code is not easily understood by IDE&#8217;s.  While special features could be added to the IDE to support this framework, it does not inherently know what kind of object is being returned by the $dic->get(..) method call.</p>
<h3>Summary</h3>
<p>While dependency management frameworks have clear drop-in benefits, there exist a few considerations that have unknown or unexplored consequences.  For example, if the benefit is such that all dependencies are managed, and all a developer has to do is configure it, does that encourage deeper object graphs when creating classes and class dependencies?  If so, what is the performance impact of these deep object graphs, particularly on the PHP platform.  What are the memory implications of such object graphs, what are the speed implications of them?  Furthermore, if one needed to debug an object that has been generated by a dependency management framework, is that easily possible?</p>
<p>At the end of the day, whether or not to use a dependency management framework is a matter of cost versus benefit.  In order to be able to make an informed decision, a developer should consider a few scenarios. First, one should know what code might look like with and without this new framework.  This will give an indication of the cost/benefit at the code level, does it actually save lines of code, and developer headaches?  Secondly, one should consider how much added knowledge a developer or a team of developers need in order to understand this framework. Lastly, one should consider what kind of performance impact implementing this new framework has on the application&#8217;s throughput.</p>
<div class="shr-publisher-144"></div><!-- Start Shareaholic LikeButtonSetBottom --><!-- End Shareaholic LikeButtonSetBottom -->]]></content:encoded>
			<wfw:commentRss>http://ralphschindler.com/2011/05/18/learning-about-dependency-injection-and-php/feed</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>PHP Component and Library API Design Overview</title>
		<link>http://ralphschindler.com/2011/01/18/php-component-and-library-api-design-overview</link>
		<comments>http://ralphschindler.com/2011/01/18/php-component-and-library-api-design-overview#comments</comments>
		<pubDate>Tue, 18 Jan 2011 22:48:00 +0000</pubDate>
		<dc:creator>Ralph Schindler</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Software Architecture]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://ralphschindler.com/?p=134</guid>
		<description><![CDATA[There&#8217;s been lots of change in the PHP community over the past few years. PHP now has namespaces. More PHP developers are using an IDE. More PHP developers are pulling inspiration from the Java, C#/.NET, and Ruby communities. And even more PHP developers are embracing the object-oriented and, ironically, the functional nature (closures) of PHP. [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop --><!-- End Shareaholic LikeButtonSetTop --><p>There&#8217;s been lots of change in the PHP community over the past few years.  PHP now has namespaces.  More PHP developers are using an IDE.  More PHP developers are pulling inspiration from the Java, C#/.NET, and Ruby communities.  And even more PHP developers are embracing the object-oriented and, ironically, the functional nature (closures) of PHP.  All these changes make for interesting code.  What has also happened is that better and more readable code is being produced by this ever growing PHP community.  It&#8217;s been a long time since &#8220;PHP application&#8221; meant a series of <a href="http://martinfowler.com/eaaCatalog/transactionScript.html">transaction scripts</a> as a mix of SQL, CSS, JS, with some PHP sprinkled in, and a couple of few classes for good measure.  Of course, that still exists, but you no longer need to go to the ends of the earth to find non-spaghetti code that is understandable within a few minutes.</p>
<p>For the most part, all of these changes are good changes.  The number of good/senior/expert level PHP developers is ever increasing and there are more and more &#8220;enterprise grade&#8221; frameworks and libraries that are being produced.  That said, with all of these new changes, the one area which is still fairly inconsistent from project to project is the naming conventions that are employed inside PHP 5.3 project that utilize namespaces.  This article will attempt to describe what an API is, how names and object-oriented features affect an API, and how various decisions affect the consumers of a particular API is.</p>
<h4>What Is An API?</h4>
<p>Before we jump into naming, it&#8217;s important to have a common understanding of the actual problem area.  When we talk about names, we are really talking about the API.  <em>An API is</em> a particular set of rules and specifications that a developer can follow to access and make use of the services and resources provided by another particular software program, component or library.  Put another way, it is an interface between various software pieces and facilitates their interaction, similar to the way the user interface facilitates interaction between humans and computers.</p>
<p>For PHP 4 / procedural based libraries, the API is defined by the functions that are declared for usage in that library.  It is further described by the global names and global state that the library utilizes to do its job.  Typically, API&#8217;s based on purely function based libraries are far simpler to understand.</p>
<p>Object-oriented API&#8217;s are a bit more complex.  When you build an object-oriented library or component, you are typically designing <em>two</em> API&#8217;s at the same time, whether or not you know it.  This is the nature of object-oriented languages when you employ the use of abstract classes and interfaces in your design.</p>
<p>The first API, the more common of the two, I call the <em>Consumption API</em>.  This is the API that answers the question: &#8220;how do people consume this thing.&#8221;  The answer to this question is generally situated around the great majority of use cases that were identified by the author of the software component/library.  In PHP, consumption might look like this:</p>
<pre class="brush: php; title: ; notranslate">
$foo = new SomeCompany\FooComponent\FooComponent($options);
$foo-&gt;setAdapter(new SomeCompany\FooComponent\Adapter\SomeAdapter($adapterOptions));
$interestingResult = $foo-&gt;doSomethingInteresting();
</pre>
<p>As you can see, <em>no</em> declarative code was required to fulfill the most common use case that was identified as a need for this component&#8217;s existence.  The above API is defined by the totality of all the public (concrete) classes, their public properties and public methods.  By examining these elements, a good API design  should allow a developer to deduce how the component works without examining <em>any</em> documentation.  When that is possible, the API has become the documentation as well as the &#8220;story&#8221; behind how the component/library is to be used.</p>
<p>Not all use cases are accounted for in generic components and generic libraries.  As developers, we attempt to create generic libraries and components that will solve the majority of problems of the majority of the community.  We cannot envision all use cases or even edge cases behind a particular component.  That said though doesn&#8217;t means that the outlying use cases are unimportant or should be unaccounted for.  These use cases are handled by the secondary API: the <em>&#8220;Extension API&#8221;</em>.</p>
<p>The Extension API answers the question: &#8220;since this component does 90% of what I want, how can I extend it to fulfill the last few of my needs.&#8221;  Clearly, it makes sense to leverage tools that do most of what you need especially if they can be extended in ways that are outside of the out-of-the-box feature-set.  Object-oriented/class based code is particularly well suited to extension through the principle of <i>overriding polymorphism</i>.</p>
<p>The primary tool behind overriding polymorphism is method overriding.  For this to be possible, base types, or the types that are shipped with the component/library you are extending, will be overridden to fulfill this new behavior that is your specialized use case.  Consider the following code example:</p>
<pre class="brush: php; title: ; notranslate">
namespace MyCompany\FooComponent\Adapter; // My Component
use SomeCompany\FooComponent\Adapter\SomeAdapter; // Consumed Component

// extend the provided Component with my special use case
class MyAdapter extends SomeAdapter
{
    protected function _someWorkToBeDone()
    {
        // do something special that fulfills our use case
        return parent::_someWorkToBeDone();  // protected method on parent class
    }
}
</pre>
<p>As you can see here, we&#8217;ve extended the functionality of the base adapter from the shipped component/library with our own functionality.  This is possible since the base adapter tucked away the business logic we needed to alter inside a <em>protected</em> method.  This is what allows us to rely on overriding polymorphism to extend code to suit more specific needs.  This &#8220;Extension API&#8221; can therefore be defined by the totality of all <em>protected</em> members of a class: methods and properties that can be utilized in child classes.  These protected methods are not all that important or even useful in the documented and de-facto use cases of a component, but become extremely important when extending.</p>
<h4>API Philosophy</h4>
<p>It&#8217;s hard to quantify importance of any one aspect of a codebase&#8217;s API over another without first talking about the general philosophy.  In the land of a 1000 frameworks and libraries, being well written and poorly written divides the great majority of them.  Of what is left of the (generally regarded) well written ones, philosophy divides the rest.</p>
<p>There exist two common philosophical &#8220;goals&#8221; that most libraries/components generally subscribe to that, depending on your perspective, might be contradictory.  For arguments sake, let&#8217;s assume that each is as important as the other.  The first: &#8220;easy to use&#8221;.  A component&#8217;s like-ability by developers is greatly determined by how easy something is to use, if it&#8217;s intuitive, if it&#8217;s fulfills the majority of one&#8217;s needs.  The other: &#8220;easy to extend&#8221;.  The majority of the time, a component is written for some well known use cases.  Generally, that will suite the majority of the needs of any one developer, but there are always some unknown use cases.  A components ability to be able to deliver a mostly working solution while allowing the developer to extend it for the unknown is what determined how easy it is to extend said component.</p>
<p>More often than not, ease of use and extensibility live at two ends of the spectrum.  Things that are easy to use are generally hard to extend, and things that are simple to extend are generally harder to use.  This is the case because to accommodate one usually comes at the expense of the other.</p>
<p>Getting back to philosophy and this example at hand, both ease of use and extensibility are both equally important.  The goal, in terms of API design, is to be able to accommodate each equally and strike a balance between the two so that each goal is represented in the API.</p>
<h4>Basic Tips And Tricks For Better APIs</h4>
<p>The tips and tricks for building better component API&#8217;s could get fairly long, so this article will attempt to cover some of the more &#8220;basic&#8221; ideas.</p>
<h5>Adopt A Common Namespace &amp; Class Naming Scheme</h5>
<p>While it is true that the PHP platform has no built-in packaging, or file based import mechanism&#8230; the PHP autoloader with the help of some common conventions can get you 99% of the way there.  Large projects like Zend Framework, Symfony, PHPUnit, and PEAR have all settled on a pretty simple and common naming scheme based on the PEAR naming standards.  By utilizing this naming scheme, your code will be instantly familiar to developers who already have knowledge of this scheme in other projects.  The benefit here is that developers will know exactly where to find classes inside the filesystem.</p>
<pre class="brush: php; title: ; notranslate">
namespace MyCompany\MyComponent;
class Foo {
    // will be found relative to the include_path, or some path
    // managed by an autoloader at
    // MyCompany/MyComponent/Foo.php, pretty simple eh?
}
</pre>
<h5>Avoid Doing Too Much In the Constructor</h5>
<p>There&#8217;s lots of places on the web that discuss this, so I&#8217;ll <a href="http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/">link</a> to <a href="http://usrportage.de/archives/897-Antipattern-the-verbose-constructor.html">them</a> <a href="http://www.beaconhill.com/kb/java/code-in-constructor-anti-pattern.html">here</a> and not go into too much detail.  I&#8217;ve seen it called a &#8220;unified constructor&#8221;, but that&#8217;s not what we are talking about here, or at least, that is not the goal.  The goal is to allow the consumer to give as much or as little information about the identity of the object at instantiation time.  The common signature that I like for this is the following:</p>
<pre class="brush: php; title: ; notranslate">
class Foo
{
    public function __construct($options = null)
    {
        if (is_array($options)) {
            $this-&gt;setOptions($options);
        } elseif (is_string($options)) {
            $this-&gt;setValueThatIsDocumentAndWellKnown($options);
        }
    }
}
</pre>
<p>Generally, the call to setOptions() will in turn call various setters if they exist.  What is important is that at construction/instantiation time a consumer is not required to fulfill all of the classes requirements.  Why is this important? It reverses order in which dependencies are required to be interacted with.  Lets examine this in code:</p>
<pre class="brush: php; title: ; notranslate">
// Example 1
// assuming: class Foo { __construct(A $a, B $b, C $c) {} }
$a = new A($aOption1, $aOption2);
$b = new B();
$c = new C($cOption, $a);

$foo = new Foo($a, $b, $c); // and finally
$foo-&gt;doSomethingInteresting();

/** OR ALTERNATIVELY **/

// Example 2
// assuming: class Foo { __construct($options = null) {} }
$foo = new Foo(array(
    'a' =&gt; ($a = new A($aOption1, $aOption2)),
    'b' =&gt; new B(),
    'c' =&gt; new C($cOption, $a)
    ));
$foo-&gt;doSomethingInteresting();

// Example 3
// or better:
$foo = new Foo();
$a = new A($aOption1, $aOption2);
$foo-&gt;setA($a)
    -&gt;setB(new B())
    -&gt;setC(new C($cOption, $a));
$foo-&gt;doSomethingInteresting();
</pre>
<p>The difference is that in Example 1, even though our target use case is handled by class <tt>Foo</tt>, we are forced to interact with the dependencies first.  Conversely, examples 2 and 3 show that our target object <tt>Foo</tt> is created up front, and dependencies are handled after instantiation.  If code clarity is a goal, reading the code top down in example 2 and 3 makes more sense than in example 1 since the API has allowed the developer to code his use case in a top-down or story-like code block.  Why do I like this pattern of usage? Simple: it highlights PHP&#8217;s loose nature and flexibility in it&#8217;s use case&#8230; but mostly because it&#8217;s more readable.</p>
<h5>Avoid <tt>final</tt> And <tt>private</tt></h5>
<p>This one speaks to extensibility.  Unless you are attempting to restrict a user from utilizing some kind of use case, there is little gain in marking members as <tt>final</tt> or <tt>private</tt>.  Sooner or later, someone somewhere will need to override a method you&#8217;ve implemented for some obscure use case.  A better approach is to provide them with a codebase that will meet most of their needs and can be extended to fulfill the rest if they are outside the original scope.  That way, they are not forced to patch your codebase.</p>
<h4>Summary</h4>
<p>This is by far <em>not</em> an exhaustive list.  As more of the larger projects move to using namespaces, closures and the other PHP 5.3 features, we&#8217;ll start to see a few more best-practices emerge as they relate to API design.  In the mean time, this overview will serve as a springboard for a few discussions on API design moving forward with ZF2 and PHP 5.3 component development that is currently on-going.</p>
<div class="shr-publisher-134"></div><!-- Start Shareaholic LikeButtonSetBottom --><!-- End Shareaholic LikeButtonSetBottom -->]]></content:encoded>
			<wfw:commentRss>http://ralphschindler.com/2011/01/18/php-component-and-library-api-design-overview/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Exception Best Practices in PHP 5.3</title>
		<link>http://ralphschindler.com/2010/09/15/exception-best-practices-in-php-5-3</link>
		<comments>http://ralphschindler.com/2010/09/15/exception-best-practices-in-php-5-3#comments</comments>
		<pubDate>Wed, 15 Sep 2010 20:21:18 +0000</pubDate>
		<dc:creator>Ralph Schindler</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Software Architecture]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://ralphschindler.com/?p=107</guid>
		<description><![CDATA[Every new feature added to the PHP runtime creates an exponential number of ways developers can use and abuse that new feature-set. However, it’s not until developers have had that chance that some agreed-upon good usage and bad usage cases start to emerge. Once they do emerge, we can finally start to classify them as [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop --><!-- End Shareaholic LikeButtonSetTop --><p>Every new feature added to the PHP runtime creates an exponential number of ways developers can use and abuse that new feature-set. However, it’s not until developers have had that chance that some agreed-upon good usage and bad usage cases start to emerge. Once they do emerge, we can finally start to classify them as best or worst practices.</p>
<p>Exception handling in PHP is not a new feature by any stretch.  In this article, we&#8217;ll discuss two new features in PHP 5.3 based around exceptions.  The first is nested exceptions and the second is a new set of exception types offered by the SPL extension (which is now a core extension of the PHP runtime).  Both of these new features have found their way into the book of best best practices and deserve to be examined in detail.</p>
<p>Special note: some of these features have existed in PHP &lt; 5.3 or are at least capable of being implemented in PHP &lt; 5.3.  When this article mentions PHP 5.3, it is not in the strictest sense of the PHP runtime.  Instead, it is meant that code bases and projects that are adopting PHP 5.3 as a minimum version but also all of the best practices that have emerged in this new phase of development.  This phase of development highlighted by the &#8220;2.0&#8243; efforts of projects like Zend Framework, Symfony, Doctrine and PEAR to name a select few.</p>
<h3>Background</h3>
<p>Previously in PHP 5.2, there was a single exception class Exception.  Generally, speaking from a Zend Framework / PEAR coding standard perspective, this exception class became the root for all exceptions that might be thrown from within your library.  For example, if you created a library for your company MyCompany, then you would, according to ZF/PEAR standards, have prefixed all code with <tt>MyCompany_</tt>.  For this library, you might create a base exception for your library code: <tt>MyCompany_Exception</tt>, which extends the PHP class <tt>Exception</tt> and from which all your components might inherit, subclass, and throw.  So, if you created a component <tt>MyCompany_Foo</tt>, it might have a base exception class called <tt>MyCompany_Foo_Exception</tt> that is expected to be thrown from within the <tt>MyCompany_Foo</tt> component.  These exceptions can be caught by attempting to <i>catch</i> <tt>MyCompany_Foo_Exception</tt>, <tt>MyCompany_Exception</tt>, or simply <tt>Exception</tt>.  This would allow 3 levels of granularity (or more depending on how many times the <tt>MyCompany_Foo_Exception</tt> was subclassed) to consumers of this component in this particular library, and handle that exception in a way they deem fit.</p>
<h3>New Feature: Nesting</h3>
<p>In PHP 5.3, the base exception class now <a href="http://us3.php.net/manual/en/language.exceptions.extending.php">handles <i>nesting</i></a>.  What is nesting? Nesting is the ability to catch a particular exception, create a new exception object to be thrown with a reference to the original exception.  This then allows the caller access to both the exception thrown from within the consumed library of the more well known type, but also access to the exception that originated this exceptional behavior as well.</p>
<p>Why is this useful?  Typically, this is most useful in code that consumes other code that throws exceptions of its own type.  This might be code that utilizes the <A href="http://en.wikipedia.org/wiki/Adapter_pattern">adapter pattern</a> to wrap 3rd party code to deliver some kind of adaptable functionality, or simply code that utilizes some exception throwing PHP extension.</p>
<p>For example, in the component <a href="http://framework.zend.com/manual/en/zend.db.html">Zend_Db</a>, it uses the adapter pattern to wrap specific PHP extensions in order to create a database abstraction layer.  In one adapter, <tt>Zend_Db</tt> wraps PDO, and PDO throws its own exception <tt>PDOException</tt>, <tt>Zend_Db</tt> needs to catch these PDO specific exceptions and re-throw them as the expected and known type of <tt>Zend_Db_Exception</tt>.  This gives developers the assurance that <tt>Zend_Db</tt> will always throw exceptions of type <tt>Zend_Db_Exception</tt> (so it can be caught), but they will also have access to the original PDOException that was thrown in case it is needed.</p>
<p>The following is an example of how a fictitious database adapter might implement nested exceptions:</p>
<pre class="brush: php; title: ; notranslate">

class MyCompany_Database
{
    /**
     * @var PDO object setup during construction
     */
    protected $_pdoResource = null;

    /**
     * @throws MyCompany_Database_Exception
     * @return int
     */
    public function executeQuery($sql)
    {
        try {
            $numRows = $this-&gt;_pdoResource-&gt;exec($sql);
        } catch (PDOException $e) {
            throw new MyCompany_Database_Exception('Query was unexecutable', null, $e);
        }
        return $numRows;
    }

}
</pre>
<p>To utilize a nested exception, you would call the <tt>getPrevious()</tt> method of the caught exception:</p>
<pre class="brush: php; title: ; notranslate">

// $sql and $connectionParameters assumed
try {
    $db = new MyCompany_Database('PDO', $connectionParams);
    $db-&gt;executeQuery($sql);
} catch (MyCompany_Database_Exception $e) {
    echo 'General Error: ' . $e-&gt;getMessage() . &quot;\n&quot;;
    $pdoException = $e-&gt;getPrevious();
    echo 'PDO Specific error: ' . $pdoException-&gt;getMessage() . &quot;\n&quot;;
}
</pre>
<p>Most recent PHP extensions have OO interfaces.  As such, those API&#8217;s tend to lean on throwing exceptions instead of raising errors.  A short list of exception throwing extensions in PHP include PDO, DOM, Mysqli, Phar, Soap and SQLite.</p>
<h3>New Feature: New Core Exception Types</h3>
<p>Also in PHP 5.3 development we are shining a light on some new and interesting Exception types.  These exceptions have been in place since the PHP 5.2.x, but it has not been till recently and the &#8220;re-evaluation&#8221; exception best practices that they are now gaining some limelight.  They are implemented in the SPL extension and are listed on the manual pages located <a href="http://us.php.net/manual/en/spl.exceptions.php">here</a>.  Since these new exception types are part of core PHP as part of SPL, they can be used by anyone who targets PHP 5.3 as the minimum runtime for their code.  While this might seem less important for when writing application layer code, the way we adopt and use these new exception types becomes even more important when we are writing and consuming library code.</p>
<p>So why new exception types in general?  Previously, developers attempted to give more meaning to their exceptions by putting more information into the message of the exception.  While this is good, it has a few drawbacks.  One is that you cannot catch an exception based on a message.  This can be a problem if you know a set of code is throwing the same exception type with various message for various exceptional conditions that can be handled differently.  For example, an authentication class that during <tt>$auth->authenticate();</tt> it throws the same type of exception (let&#8217;s assume Exception), but with different messages for two specific failures: a failure where the authentication server cannot be reached and the same exception type but different message for a failed authentication attempt.  In this case (nevermind that using Exceptions might not be the best way to handle authentication responses), it would require string parsing the message to handle those two scenarios differently.</p>
<p>The solution to this is clearly some way to codify exceptions so that they can be easily interrogated when trying to discern how to react to this exceptional situation.  The first response libraries have had is to use the <tt>$code</tt> property of the Exception base class.  The other is to create multiple types, or new exception classes, that can be thrown to describe the behavior.  Both of these approaches have the same simple drawback.  Neither has emerged as a best practice and as such, neither is considered a standard, thus each project attempting to replicate this solution might do so with small variations that force the consumer to go back to the documentation to understand the library specific solution that was created.  Now with the new types approach in the SPL, otherwise known as the <i><b>Standard</b> PHP Library</i>; developers can utilize these new types in the same way in their projects and the projects they are consuming since a best practice for these new types has emerged.</p>
<p>The second drawback of the detailed message approach is that it makes understanding the exceptional situation harder for non-english or limited-english speaking developers.  This might slow down some developers when trying to decipher what an exception message is trying to convey.  As many developers as there are writing exceptions, there are equally as many variations in how they will describe that situation in the message since there is no standard for conformity or for codification.</p>
<h4>So How Do I Use Them, Give Me The Dirty Details?</h4>
<p>There are a total of 13 new exceptions in the SPL.  Two of them can be considered &#8220;base&#8221; types: <tt>LogicException</tt> and <tt>RuntimeException</tt>; both extend the PHP <tt>Exception</tt> class.  The remainder of the methods can thusly be broken down into three logical groups: the <em>dynamic call</em> group, the <em>logic</em> group and the <em>runtime</em> group.</p>
<p>The <em>dynamic call</em> group contains the exceptions <tt>BadFunctionCallException</tt> and <tt>BadMethodCallException</tt>.  <tt>BadMethodCallException</tt> is a subclass of <tt>BadFunctionCallException</tt> which in turn is a subclass of <tt>LogicException</tt>.  That means that these exceptions can be caught by either their direct type, <tt>LogicException</tt>, or simply <tt>Exception</tt>.  When do you use these?  Generally, these should be used when an exceptional situation arises as a result of an unresolvable __call() during a method or when a callback cannot find a valid function to call (or better put, when something is not <tt>is_callable()</tt>).</p>
<p>For example:</p>
<pre class="brush: php; title: ; notranslate">

// OO variant
class Foo
{
    public function __call($method, $args)
    {
        switch ($method) {
            case 'doBar': /* ... */ break;
            default:
                throw new BadMethodCallException('Method ' . $method . ' is not callable by this object');
        }
    }

}

// procedural variant
function foo($bar, $baz) {
    $func = 'do' . $baz;
    if (!is_callable($func)) {
        throw new BadFunctionCallException('Function ' . $func . ' is not callable');
    }
}
</pre>
<p>While the direct example is inside <tt>__call</tt> and anywhere near something that will <tt>call_user_func()</tt>, this group of exceptions are also useful when developing any kind of API where dynamic method call and function call lookups are utilized.  An example of this would be a SOAP or XML-RPC client/server who is capable of issuing and/or interpreting method requests.</p>
<p>The second group is the <em>logic</em> group.  This group consists of <tt>DomainException</tt>, <tt>InvalidArgumentException</tt>, <tt>LengthException</tt>, and <tt>OutOfRangeException</tt>.  These exceptions are a subclass of <tt>LogicException</tt> which is in turn a subclass of the PHP <tt>Exception</tt> class.  You use these exceptions when there is an exceptional situation that arises from either a mutation of state or as a result of bad method or function parameters.  To get a better understanding of this, we will first look at the last group of exceptions.</p>
<p>The final group is the <em>runtime</em> group.  It consists of <tt>OutOfBoundsException</tt>, <tt>OverflowException</tt>, <tt>RangeException</tt>, <tt>UnderflowException</tt>, and <tt>UnexpectedValueException</tt>.  These exceptions are a subclass of <tt>RuntimeException</tt> which is in turn a subclass of the PHP <tt>Exception</tt> class.  These exception should be used when an exceptional situation arises during the &#8220;runtime&#8221; of a function or method call.</p>
<p>How do these logic group and runtime group work together?  If you look at the anatomy of an object, one of two things is generally happening. First, the object will be tracking and mutating state. This means the object is generally not doing anything (yet); it might have configuration passed to it; it might be setting up properties (via setters and getters); or, it might be getting references to other objects. Second, when the object is not tracking and mutating state, it is operating – doing what it was designed to do. This is the object’s <i>runtime</i>.  For instance, during the objects lifetime, it might be created, passed a configure object, then it might have setFoo($foo), setBar($bar) called.  During these times any kind of <tt>LogicException</tt> should be raised.  In addition, when the object is asked to do something, with parameters, for example $object->doSomething($someVariation);  during the first few lines when it interrogates that $someVariation variable, it would throw a <tt>LogicException</tt>.  After it is done interrogating $someVariation, and it goes on about doing its job of doSomething(), this is considered its &#8220;runtime&#8221; and in this code it would throw <tt>RuntimeExcpetion</tt>s.</p>
<p>To better understand, we&#8217;ll look at this concept in code:</p>
<pre class="brush: php; title: ; notranslate">

class Foo
{
    protected $number = 0;
    protected $bar = null;

    public function __construct($options)
    {
        /** this area throws LogicException types **/
    }

    public function setNumber($number)
    {
        /** this method throws LogicException types **/
    }

    public function setBar(Bar $bar)
    {
        /** this method throws LogicException types **/
    }

    public function doSomething($differentNumber)
    {
        if ($differentNumber != $expectedCondition) {
            /** this area throws LogicException types **/
        }

        /**
         * From here on down, this method throws
         * RuntimeException types
         */
    }

}
</pre>
<p>Now that this concept is understood, what does this do for a consumer of this code base?  The caller can be sure that anytime they are mutating the state of an object, they can catch exceptions with the most specific type, for example <tt>InvalidArgumentException</tt> or <tt>LengthException</tt>, and at least <tt>LogicException</tt>.  By having this level of granularity, and multiple types involved, they can catch the exception minimally with LogicException, but also get greater understanding of what when wrong via the actual type of the exception.  This same concept applies for the Runtime group of exceptions as well, more specific types can be thrown and either the specific or the less specific type will be caught.  This offers a greater deal of knowledge about the situation and granularity of control to the caller.</p>
<p>Below is a table of the information you might find of interest concerning these SPL exceptions</p>
<h3>Best Practices In Library Code</h3>
<p>Since the advent of these new exception types in PHP 5.3, a new best practice for library code has also emerged.  While it is most beneficial to get a standard specialized exception type like <tt>InvalidArgumentException</tt> or <tt>RuntimeException</tt>, it would also be useful to catch component level exceptions.  You can read a more in-depth discussion of the concepts on the <a href="http://framework.zend.com/wiki/display/ZFDEV2/Proposal+for+Exceptions+in+ZF2?showComments=false">ZF2 wiki</a> or the <a href="http://wiki.php.net/pear/rfc/pear2_exception_policy">PEAR2 wiki</a>.</p>
<p>The long and short of this, in addition to the best practices listed above, is that there should be a component level type that can be caught for any exception that emanates.  This is accomplished by using what is known as a <a href="http://en.wikipedia.org/wiki/Marker_interface_pattern">Marker Interface</a>.  By creating a component level marker interface, real exception types inside a given component can extends the SPL exception types and be caught by any number of class types at runtime.  Let&#8217;s examine the following code:</p>
<pre class="brush: php; title: ; notranslate">

// usage of bracket syntax for brevity
namespace MyCompany\Component {

    interface Exception
    {}

    class UnexpectedValueException
        extends \UnexpectedValueException
        implements Exception
    {}

    class Component
    {
        public static function doSomething()
        {
            if ($somethingExceptionalHappens) {
                throw new UnexpectedValueException('Something bad happened');
            }
        }
    }

}
</pre>
<p>Assuming the above code, if one were to execute <tt>MyCompany\Component\Component::doSomething()</tt>, the exception that is emitted from the <tt>doSomething()</tt> method can be caught by any of the following types: PHP&#8217;s <tt>Exception</tt>, SPL&#8217;s <tt>UnexpectedValueException</tt>, SPL&#8217;s <tt>RuntimeException</tt> the component&#8217;s <tt>MyCompany\Component\UnexpectedValueException</tt>, or the component&#8217;s <tt>MyCompany\Component\Exception</tt>.  This affords the caller any number of opportunities to catch an exception that emanates from a given component within your library.  Furthermore, by analyzing the types that make up the exception, more semantic meaning can be given to the exceptional situation that just occurred.</p>
<h3>Summary</h3>
<p>In summary, this article should help guide you in creating and throwing more meaningful exceptions in a standards based and best practices way by negating the emphasis of the exception message and putting more emphasis on the exception type.  If you&#8217;d like to carry on the discussion of these concepts feel free to comment here, on the PHP documentation pages, or in the ZF2 wiki comments section for the Exception proposal linked above.</p>
<div class="shr-publisher-107"></div><!-- Start Shareaholic LikeButtonSetBottom --><!-- End Shareaholic LikeButtonSetBottom -->]]></content:encoded>
			<wfw:commentRss>http://ralphschindler.com/2010/09/15/exception-best-practices-in-php-5-3/feed</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>PHPundamentals Series: A Background on Statics (Part 1 on Statics)</title>
		<link>http://ralphschindler.com/2010/05/06/phpundamentals-series-a-background-on-statics-part-1-on-statics</link>
		<comments>http://ralphschindler.com/2010/05/06/phpundamentals-series-a-background-on-statics-part-1-on-statics#comments</comments>
		<pubDate>Thu, 06 May 2010 14:59:55 +0000</pubDate>
		<dc:creator>Ralph Schindler</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[PHPundamentals]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Software Architecture]]></category>
		<category><![CDATA[Software Engineering]]></category>

		<guid isPermaLink="false">http://ralphschindler.com/?p=86</guid>
		<description><![CDATA[Just beyond reading the title, you&#8217;ve more than likely come to this article as the curious yet uninformed, the mad and raving lunatic, or as an enlightened one. Static class members (from here on called simply, &#8220;statics&#8221;) in PHP conjure both the best and worst in developers for a variety of reasons. In part 1 [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop --><!-- End Shareaholic LikeButtonSetTop --><p>Just beyond reading the title, you&#8217;ve more than likely come to this article as the <em>curious yet uninformed</em>, the <em>mad and raving lunatic</em>, or as <em>an enlightened one</em>.  Static class members (from here on called simply, &#8220;statics&#8221;) in PHP conjure both the best and worst in developers for a variety of reasons.  In part 1 of this series of articles on statics, we&#8217;ll explore some background to get a better understanding of statics in PHP.</p>
<h4>Some <em>Static</em> Background And Understanding</h4>
<p>Before we can move into the arguments that surround statics, we first need to understand what they are in the context of PHP.  The core of the PHP language and runtime can draw some pretty big corollaries from the Java/JVM and C#/.NET language platforms.  The biggest, and most important for the purposes of this article, is PHP&#8217;s object model.  Like Java and .NET, PHP follows a class-based, single-inheritance, multiple-interface model- a tenet described by the grandfather of OO languages: <a title="Smalltalk" href="http://en.wikipedia.org/wiki/Smalltalk">smalltalk</a>.  Of course, PHP applies its own &#8220;perspective&#8221; when it comes to the actual implementation details in that of typing, casting, mixed-paradigm usage, and so on; but the foundation for the object model is clearly defined.</p>
<p>That said, it is easy for the PHP community to draw comparisons and, more importantly, &#8220;borrow&#8221; best practices from both the Java and .NET communities.  We certainly have borrowed our fair share with regards to development time tools, infrastructure tools and design patterns.  Over the past 5 to 7 years, there has been an increasing adoption of best practices and patterns from the enterprise Java community, particularly in the form of two major texts: GoF and PoEAA.  The GoF (<a title="Gang Of Four / Design Patterns" href="http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1273084312&amp;sr=1-1">Gang of Four</a>) text primarily discusses best practices in the form of code structure and reuse: factory, singleton, adapter, composite, facade, iterator and observer to name a few.  PoEAA (<a title="Patterns of Enterprise Application Architecture" href="http://www.amazon.com/exec/obidos/ASIN/0321127420">Patterns of Enterprise Application Architecture</a>), on the other hand, attempts to solve higher order problems, particularly architectural problems at the application layer: MVC, Page Controller, Front Controller, Domain Model, Table and Row Gateway, and so on.  While the examples are primarily executed in Java, they are structurally similar when implemented in PHP, so much so that PHP developers can read the Java examples as pseudo-code.  This is what makes these patterns so applicable and thus popular in the PHP community.</p>
<p>Since we now know where these usage patterns originated, we should have a look at the target language platform: PHP.  The key concept which delineates the PHP platform from the JVM and .NET platforms, is that PHP by default assumes a <a title="Shared-Nothing Architecture" href="http://en.wikipedia.org/wiki/Shared_nothing_architecture">shared-nothing architecture</a>.  What does this mean?  It means out of the box, PHP is not a persistent application platform.  PHP&#8217;s runtime is built around the notion of primarily solving the web problem.  In turn, since the web is request driven, you might say that an application written in PHP is also request driven.  Put another way, the scope of your application is bound to a single request.  The shared-nothing aspect means that the state of the application is built-up and torn-down upon the start and completion of each request to your application.  Conversely, Java and .NET offer a persistent application stack which means the application&#8217;s state exists separate from the requests that come in via the web server.  So, in PHP, the many requests each contain a single running instance of your application.  In Java/.NET, the single application running handles the many requests.</p>
<h4>Statics in Analogies</h4>
<p>Still don&#8217;t get it? Let&#8217;s talk in a couple of analogies.  Let&#8217;s assume we&#8217;ve built a basic application with the &#8220;out-of-the-box&#8221; technologies offered; one built on top of PHP and the other built on top of Java (or .NET, you can choose.)  With your Java/.NET application, if a request is never received from your web server, the application <strong>is</strong> indeed still running.  In PHP, if a request is never received from your web server, the application has NEVER run.  The runtime of a Java/.NET application might be hours or days, whereas the runtime of a PHP application is a long as it takes to service the request.  This analogy&#8217;s mileage may vary, and it is surely intended for demonstrative purposes.  You could inject any number of monkey wrenches into it, but for all intents and purposes- it&#8217;s correct and it works.</p>
<p>Understanding the full scope of an applications runtime state is the most important aspect into understanding the role of static class members in OO programming.  Static class members live as long as the application runtime is valid and alive.  What this means it is that any class member state that has been set during any operation during the applications runtime will persist until the application ceases to exist.  Looking back at our main platform differences, we can see that in the Java/.NET platform, statics members created in the scope of an application layer will be around until someone pushes the &#8220;shutdown&#8221; button on that application.  This could mean a static member or static state is persisted for hours, days, or even longer.  Like these persistent application stacks, PHP will destroy any static members and state at the end of the applications lifecycle.  Unlike these persistent application stacks, the application lifecycle ends with the completion of a web request.  This means that static members and static state in PHP, for the average web application, sticks around for seconds or less and is only valid in the context of a single web request.</p>
<h4>Statics in Pictures</h4>
<p><em>Still</em> don&#8217;t get it?  Lets have a look at a few images to better explain these concepts.</p>
<p>The following images will attempt to explain the various layers of a web application, one from the perspective of the JVM/.NET platform, the other from the perspective of the PHP platform. (For all intents and purposes, the PHP platform could also be any scripting language executed by an apache module or fastcgi.)</p>
<p>The <span style="color: #339966;">green</span> layer is the web server layer, this is the process that will attach to port 80 and listen for requests.  The <span style="color: #0000ff;">blue</span> layer represents the application process itself.  This layer is responsible for global application state and class-based static state.  The <span style="color: #ff6600;">orange</span> layer is a request which comes in from the web, this is typically what we&#8217;ve called a page request.  Inside of each web request is the <span style="color: #ffff00;">yellow</span> layer, which represents the page-lifecycle.  In terms of the application, this is where all of the request specific application routines happen including page startup and business logic.</p>
<p><a href="http://ralphschindler.com/wordpress/wp-content/uploads/2010/05/Java-and-.NET-Application-Architecture.png"><img class="aligncenter size-full wp-image-90" title="Java and .NET Application Architecture" src="http://ralphschindler.com/wordpress/wp-content/uploads/2010/05/Java-and-.NET-Application-Architecture.png" border="0" alt="" width="596" height="363" /></a></p>
<p>Contrasted against &#8230;</p>
<p><a href="http://ralphschindler.com/wordpress/wp-content/uploads/2010/05/PHP-Application-Architecture.png"><img class="aligncenter size-full wp-image-89" title="PHP Application Architecture" src="http://ralphschindler.com/wordpress/wp-content/uploads/2010/05/PHP-Application-Architecture.png" border="0" alt="" width="596" height="404" /></a></p>
<p>The most important thing to take away from these images, particularly with respect to understanding statics, is the <span style="color: #0000ff;">blue</span> layer, or the layer that best represents the scope of globals and static members.  This is the heart of what is meant by a &#8220;shared-nothing&#8221; architecture.  It is this key difference that affects how we architect the code for our web applications.</p>
<p>In the next article in this series, we&#8217;ll have a look at PHP&#8217;s application architecture in greater detail and how it solves problems that might arise from a shared-nothing style architecture, why this architecture is arguably better for the web and cloud based services, but most importantly, how statics fit into this paradigm.</p>
<div class="shr-publisher-86"></div><!-- Start Shareaholic LikeButtonSetBottom --><!-- End Shareaholic LikeButtonSetBottom -->]]></content:encoded>
			<wfw:commentRss>http://ralphschindler.com/2010/05/06/phpundamentals-series-a-background-on-statics-part-1-on-statics/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>The Anatomy Of A Bug/Issue Reproduction Script</title>
		<link>http://ralphschindler.com/2010/02/18/the-anatomy-of-a-bug-issue-reproduction-script</link>
		<comments>http://ralphschindler.com/2010/02/18/the-anatomy-of-a-bug-issue-reproduction-script#comments</comments>
		<pubDate>Thu, 18 Feb 2010 22:17:14 +0000</pubDate>
		<dc:creator>Ralph Schindler</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Quality Assurance]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://ralphschindler.com/?p=60</guid>
		<description><![CDATA[&#8220;There is a problem with component Fooey-Bar-Bazzy, I think it&#8217;s related to Nanny-Nanny-Neener. Please Fix Now.&#8221; If you&#8217;ve written a bug/issue report like that in the past with no other details- shame on you! This may come as a shock, but as great as some developers might be, they cannot read minds. Each has their [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop --><!-- End Shareaholic LikeButtonSetTop --><p>&#8220;There is a problem with component Fooey-Bar-Bazzy, I think it&#8217;s related to Nanny-Nanny-Neener. Please Fix Now.&#8221; If you&#8217;ve written a bug/issue report like that in the past with no other details- shame on you!  This may come as a shock, but as great as some developers might be, they cannot read minds.  Each has their own way of coding, custom working environment as well as their own favorite tools; aside from variances in coding standards and best practices.  Some could argue these little intricacies are outside of the realm of coding standards and best practices and that these are the differences between good, great, and even terrible developers.  Each developer has a different opinion on how particular applications, libraries of code, or even features of a particular project are expected to behave in practice.  These varying expectations are why bugs/issues exist.  No one developer producing code for mass consumption can anticipate every possible use case.  Additionally, no one developer can replicate every environment surrounding every pre-conceived use case.  There are simply not enough resources at hand; be it in the form of a variety of systems or simply the number of hours in a developers day.</p>
<p>With that in mind, I write this as a plea to all developers to be good to the maintainer of code you use.  In the simplest form of advice, I suggest that before you click submit on that bug/issue report form, ask yourself two questions: &#8220;Did I do enough due-diligence in determining if this is really a bug?&#8221; AND &#8220;If <b>I</b> got this bug report, would I be able to reproduce it.. let alone understand it?&#8221;.  If the answer is YES to both of those questions.  Go ahead- click submit.  If your answer is no, you&#8217;ve got some more work to do.</p>
<h3>Some Tenets Of the Good Reproduction Script</h3>
<p>In this short article, I&#8217;d like to outline a few details of what should go into a bug/issue report.  These are some simple guidelines that should be considered when you write a bug/issue report.  It should be noted that this list is by all means not exhaustive, but if you at least consider the list below before clicking submit- you&#8217;ll make a code maintainers day.  I promise. </p>
<ol>
<li><b>List Out All Assumptions Clearly</b>
<p>    PHP specifically is well known for being a &#8220;glue language&#8221;.  What that means is that PHP is generally sitting between multiple pieces of software that is, of course, <i>not PHP</i>.  This means that these pieces of software each have their own set of configurations and environments that PHP is &#8220;gluing&#8221; together.  That being the case, any assumptions <em>about non-PHP assumptions should be clearly listed</em> in the reproduction script.  This could include database flavor and its settings, a PHP library component, or perhaps a specific version of an extension that is being used and the underlying unmanaged/c-based library your PHP environment is consuming.
    </li>
<li><b>Use The Shortest Possible Use Case</b>
<p>    As tempting as it is to copy a script from your project and paste it into the bug/issue submission box, don&#8217;t do this.  If you are truly invested in seeing the bug/issue fixed in a timely fashion, take the time to create a small reproduction script.  In this script should be the <em>absolute minimal amount of code</em> to demonstrate to another human that there is indeed a problem that needs solving. By keeping the script minimal and short, you are also removing any other distractions from the script that otherwise might confuse the maintainer and prevent him from fully understanding the real problem.
    </li>
<li><b>Use Generic Yet Meaningful Names</b>
<p>    It cannot be stressed enough that any non-meaningful names should be discouraged at all costs. And as mentioned above, you want to have as few distractions as possible in the use case.  For example, supplying your database table of customers, with first_name, last_name, etc has virtually nothing to do with the problem at hand.  In these cases where table and column names are ancillary to the actual problem, they should be generalized: a table named &#8216;foo&#8217;, and columns named &#8216;bar1&#8242; and &#8216;bar2&#8242;. Unless &#8230;</p>
<p>    &#8230; the variable name can add context to the problem.  What does this mean? $customer would be bad; but $faultyTableObject is good.  The latter naming makes it easy for the maintainer to focus on the variable that need to be tracked leading up to the problem.
    </li>
<li><b>Document Both What You Expect, And The Actual Result</b>
<p>    Claiming something is broken without offering what you expect and what the actual result is offers next to nothing to the maintainer attempting to fix the problem.  Generally speaking, most use cases that end up being bugs/issues are outside of the original preconceived use cases for the actual component.  That said, the maintainer is going to need the context of the use case that you&#8217;ve found to be problematic.  It also helps to point out any existing documentation that describe the more well-defined uses cases, and how your use case relates and/or deviates from those already defined use cases.
    </li>
<li><b>Make The Reproduction Script As Generic As Possible</b>
<p>    Perhaps this is redundant, but it&#8217;s important to know the minimal requirements for reproducing a bug/issue.  You are not expected to be an expert on how to fix the actual problem, but you should do your own due-diligence in order to hand the problem off to the maintainer.  It&#8217;s already been said to &#8220;List out all assumptions clearly&#8221;, but it is just as important to peel off any specific pieces of the problem that are not directly part of the problem.  </p>
<p>    This concept can best be described by example.  While MySQL is a widely available database platform, SQLite is widely known as the easiest to use and most portable database platform, at least in the PHP runtime.  If you find a problem while using mysql, but it&#8217;s clear it can be replicated using SQLite, use SQLite.  SQLite is built into PHP by default, and in a single script, you can create a memory based database and its schema in just a few lines of code.</p>
<p>    Sometimes a issue cannot be described in a single script. This is ok. This would be the case if, for example, you found an issue in a larger system, like Zend Frameworks MVC layer.  In this case, it makes sense that you need to provide a minimal ZF project to demonstrate the issue.  In these cases, make sure to again, use a few files and as little code as possible to demonstrate the issue.  Also, in the spirit of using generic code, ensure to make <em>all file system paths relative</em>. This will help the maintainer get up and running with the problematic project in a minimal amount of time, with minimal configuration.
    </li>
</ol>
<h3>A Reproduction Script By Example</h3>
<p>The following is a reproduction script I have written based on an issue (<a href="http://framework.zend.com/issues/browse/ZF-3709">ZF-3709</a>) provided to Zend Framework in our issue tracker.  I chose this issue to write a reproduction for because it offers the ability to talk about how one might go about describing the environment, more specifically what the database should look like in order to replicate the problem.</p>
<p><small>(This script can also be found at <a href="http://gist.github.com/307396">http://gist.github.com/307396</a>)</small></p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

/**
 * This reproduction script shall accompany the issue reported at
 * http://framework.zend.com/issues/browse/ZF-3709
 *
 * Assumptions:
 *   Zend_Db_Table_* from trunk
 *   PHP Environment has SQLite with :memory: capabilities
 *
 * Result:
 *   This script should run without any assertions failing (empty output)
 */

// ensure that Zend Framework trunk is being tested against &amp; classes are available
// set_include_path('/path/to/ZendFramework/library');
require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();

// setup the adapter, this uses SQLite so that its minimally invasive
// to anyone wishing to reproduce the issue on their local machine
$dbAdapter = Zend_Db::factory(
    'Pdo_Sqlite',
    array('dbname' =&gt; ':memory:')
    );

// ensure all tables have access to the adapter
Zend_Db_Table::setDefaultAdapter($dbAdapter);

// setup the database, classes, &amp; assertion system
setup();

/**
 * BEGIN Reproduction Code
 */

// find a record that has a relationship to some bars through foo_to_bar
$fooTable = new Foo();
$fooRow = $fooTable-&gt;fetchRow('id = 2');
$fooIdOnesBars = $fooRow-&gt;findManyToManyRowset('Bar', 'FooToBar');

// the expected values for the next call
$expectedValues = array(
    array('id' =&gt; '2', 'name' =&gt; 'bravo'),
    array('id' =&gt; '3', 'name' =&gt; 'charlie')
    );

// when we loop through the rows, they should match the expected results above
foreach ($fooIdOnesBars as $index =&gt; $barRow) {
    // I'll use assert here to throw warnings when expected does not match actual
    $actualValue = $barRow-&gt;toArray();
    assert($expectedValues[$index] === $actualValue);
}

/**
 * END Reproduction Code
 *
 * Supporting code below
 */ 

// setup function
function setup() {
    setup_database();
    setup_classes();
    setup_assertions();
}

// This function will setup the proper database structure with test data
function setup_database() {
    global $dbAdapter;

    $conn = $dbAdapter-&gt;getConnection();
    $conn-&gt;query('
        CREATE TABLE foo (
            id INTEGER PRIMARY KEY,
            name VARCHAR(25)
            );
        ');

    foreach (array('one', 'two', 'three', 'four') as $numberName) {
        $conn-&gt;query('INSERT INTO foo (name) VALUES (&quot;' . $numberName . '&quot;);');
    }

    $conn-&gt;query('
        CREATE TABLE bar (
            id INTEGER PRIMARY KEY,
            name VARCHAR(25));
        ');

    foreach (array('alpha', 'bravo', 'charlie', 'delta') as $word) {
        $conn-&gt;query('INSERT INTO bar (name) VALUES (&quot;' . $word . '&quot;);');
    }

    $conn-&gt;query('
        CREATE TABLE foo_to_bar (
            id INTEGER PRIMARY KEY,
            foo_id INTEGER,
            bar_id INTEGER,
            extra VARCHAR(20)
            );
        ');
    $datas = array(
        array('foo_id' =&gt; 2, 'bar_id' =&gt; 2, 'extra' =&gt; 'Two to Two'),
        array('foo_id' =&gt; 2, 'bar_id' =&gt; 3, 'extra' =&gt; 'Two to Three'),
        array('foo_id' =&gt; 3, 'bar_id' =&gt; 4, 'extra' =&gt; 'Three to Four'),
        );
    foreach ($datas as $datum) {
        $conn-&gt;query('INSERT INTO foo_to_bar '
            . '(' . implode(',', array_keys($datum)) . ')'
            . ' VALUES (&quot;' . implode('&quot;, &quot;', array_values($datum))
            . '&quot;);');
    }
}

// This function will define the proper Zend_Db_Tables and their relationships
function setup_classes() {

    class Foo extends Zend_Db_Table_Abstract
    {
        protected $_name = 'foo';
    }

    class Bar extends Zend_Db_Table_Abstract
    {
        protected $_name = 'bar';
    }

    class FooToBar extends Zend_Db_Table_Abstract
    {
        protected $_name = 'foo_to_bar';
        protected $_referenceMap = array(
            'Foo' =&gt; array(
                'columns' =&gt; 'foo_id',
                'refTableClass' =&gt; 'Foo',
                'refColumn' =&gt; 'id'
                ),
            'Bar' =&gt; array(
                'columns' =&gt; 'bar_id',
                'refTableClass' =&gt; 'Bar',
                'refColumn' =&gt; 'id'
                )
            );
    }

}

// assertion setup
function setup_assertions() {
    assert_options(ASSERT_ACTIVE, true);
    assert_options(ASSERT_WARNING, false);
    assert_options(ASSERT_CALLBACK, 'assert_failure');
}

// callback for assertion failures
function assert_failure() {
    global $expectedValues, $index, $actualValue;
    echo 'Was expecting an array that looked like:' . PHP_EOL;
    var_dump($expectedValues[$index]);
    echo 'But got array that looked like:' . PHP_EOL;
    var_dump($actualValue);
    echo PHP_EOL . PHP_EOL;
}
</pre>
<p>To the best of my ability, this script passes both of my earlier questions: &#8220;Yes, I did enough due-diligence in determining if this is really a bug.&#8221; AND &#8220;Yes, if I got this bug report, would I be able to reproduce it and understand it.&#8221;</p>
<h3>A Few Considerations</h3>
<p>This above script does not have unit tests, nor does it represent a patch to the existing framework.  While that would be the most ideal, that sets the bar much too high for people to report worthwhile issues.  The consumers of the code are not expected to be experts on the actual issue at hand, or even how to write valid unit tests that fully exercise a feature or bug.  Ultimately, as a code maintainer, I simply want to be able to see the issue you are attempting to describe.</p>
<p>If you&#8217;d like to go above and beyond the standard reproduction script, you might also considering offering lines of code that you feel might be problematic.  What that allows is maintainers to set breakpoints at specific locations and really drill down into the offending code.</p>
<p>I hope this helps developers understand what is expected of them as they file issue reports on open source code they use.  By following these guidelines you&#8217;ll be doing a service to the maintainer by making their life easier, and even your own since reproduction scripts offer quicker turn around time for issues over those that require in-depth research.</p>
<div class="shr-publisher-60"></div><!-- Start Shareaholic LikeButtonSetBottom --><!-- End Shareaholic LikeButtonSetBottom -->]]></content:encoded>
			<wfw:commentRss>http://ralphschindler.com/2010/02/18/the-anatomy-of-a-bug-issue-reproduction-script/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Dynamic Assertions for Zend_Acl in ZF</title>
		<link>http://ralphschindler.com/2009/08/13/dynamic-assertions-for-zend_acl-in-zf</link>
		<comments>http://ralphschindler.com/2009/08/13/dynamic-assertions-for-zend_acl-in-zf#comments</comments>
		<pubDate>Thu, 13 Aug 2009 14:19:10 +0000</pubDate>
		<dc:creator>Ralph Schindler</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[Zend_Acl]]></category>

		<guid isPermaLink="false">http://ralphschindler.com/?p=34</guid>
		<description><![CDATA[In Zend Framework 1.9.1, Zend_Acl gets two major issues resolved and a simple API change that now make it possible to create a more robust, more expressive ACL definition with less code. ZF issues ZF-1721 and ZF-1722, each nearly two years old, have both been solved. Over the last two years, I’ve seen a variety [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop --><!-- End Shareaholic LikeButtonSetTop --><p>In <a href="http://framework.zend.com/download/latest/">Zend Framework 1.9.1</a>, <tt>Zend_Acl</tt> gets two major issues resolved and a simple API change that now make it possible to create a more robust,  more expressive ACL definition with less code.   ZF issues <a href="http://framework.zend.com/issues/browse/ZF-1721">ZF-1721</a> and <a href="http://framework.zend.com/issues/browse/ZF-1722">ZF-1722</a>, each nearly two years old, have both been solved.  Over the last two years, I’ve seen a variety of duplicate issues come into the issue tracker, which stem from two fundamental flaws in Zend_Acl &#8211;  &#8220;Zend_Acl::isAllowed does not support Role/Resource Inheritance down to Assertions&#8221; and &#8220;Zend_Acl assertions breaks when inheritance is required (ie DepthFirstSearch)&#8221;.  In this article, we’ll explore the API changes that alleviate these two problems, and we&#8217;ll demonstrate how to leverage the <tt>Zend_Acl</tt> assertion system to create expressive, dynamic assertions that work with your applications models.</p>
<h3>Backwards Compatible API Changes</h3>
<p>Before discussing the issues, let&#8217;s go over the API change and how that affects the component.  Previously, the two methods for setting up an ACL that were used by a developer were <tt>add()</tt> and <tt>addRole()</tt>.  Interestingly, <tt>add()</tt> was intended to imply <tt>addResource()</tt>.  Since <tt>add()</tt> implied that you were adding a resource, its clear that this component was created from the perspective of resources as a primary actor, and then roles and assertions as secondary actors. </p>
<p>The new API allows for the creation of an ACL by using strings instead of having to use <tt>Zend_Acl_Role</tt> and <tt>Zend_Acl_Resource</tt> objects explicitly.  To me, this is a pretty important step towards what I&#8217;d like to see in 2.0.  In 2.0, I would ideally like to see <tt>addRole()</tt> and <tt>addResource()</tt> accept strings for <em>types</em> of roles and resources to query against, and <em>accept objects</em> for <em>explicit</em> role and resource objects to query against (even if they match an already registered type).  To put simply, I would expect <tt>addRole('user')</tt> and <tt>addRole($userObjectForRalph)</tt> to have different behaviors if different permissions were registered for each.  This would allow me to specify specific access for the user object &#8216;ralph&#8217; separately from the ACL&#8217;s for objects of role type &#8216;user&#8217;.  The behavior can be further defined to either inherit from the type, or override type ACL&#8217;s depending on the desired effect.  Ultimately, this would allow for a more dynamic experience with <tt>Zend_Acl</tt>.</p>
<h3>Dynamic Assertions Example</h3>
<p>In the following example, we&#8217;ll have a look at a common use case that is now possible in <tt>Zend_Acl</tt>.  In plain English, what developers want to be able to do is be able to design assertions that can accept application models that implement the Resource or Role interface, and be able to apply some dynamic or custom logic to assess whether or not the given role has access to the given resource.  As mentioned previously, this was not possible because in the process of checking the ACL tree, using a depth-first search, the calling resource and roles was lost, and only the original registered objects was being persisted into the assertions.  Well, that&#8217;s fixed now.</p>
<p>For the purposes of this example, we&#8217;ll take a simple concept: a user needs to be able to only edit their own blog post.  The user in this case, would be our applications model for users.  The actual class will implement the <tt>Zend_Acl_Role_Interface</tt>.  We will also have a <tt>BlogPost</tt> model which will serve as the resource in question, thus implementing the <tt>Zend_Acl_Resource_Interface</tt>.  Naturally, our system will be able to handle users of different role &#8216;types&#8217;, but our <tt>BlogPost</tt> will only be of a single resource type &#8216;blogPost&#8217;.</p>
<p>Note: the following code is demonstration only.  As such, some coding standards or conventions are not necessarily what you&#8217;d expect in proper object-oriented code or even a Zend Framework MVC based application.  Some of the code might contain rouge &#8216;echo&#8217; statements so that the demonstration below will be more expressive of what its actually doing.</p>
<pre class="brush: php; title: ; notranslate">
class User implements Zend_Acl_Role_Interface
{
    // using public members here for brevity in this article
	public $id = null;
    public $role = 'guest';

    public function getRoleId()
    {
        return $this-&gt;role;
    }
}

class BlogPost implements Zend_Acl_Resource_Interface
{
	public $id          = null;
    public $ownerUserId = null;

    public function getResourceId()
    {
        return 'blogPost';
    }
}
</pre>
<p>Next, we&#8217;ll create the dynamic assertion.  We generally would expect this assertion to be called when a <tt>User</tt> is requested to modify a <tt>BlogPost</tt>.  This assertion will ensure that the <tt>BlogPost</tt>&#8216;s owner id (the user id that owns said <tt>BlogPost</tt>), is the same as the provided <tt>User</tt> objects id.  If it is, pass, if not, fail.  Fairly common use case, right?  Here is what our assertion should look like, with a few inline comments:</p>
<pre class="brush: php; title: ; notranslate">
class UserCanModifyBlogPostAssertion implements Zend_Acl_Assert_Interface
{
    /**
     * This assertion should receive the actual User and BlogPost objects.
     *
     * @param Zend_Acl $acl
     * @param Zend_Acl_Role_Interface $user
     * @param Zend_Acl_Resource_Interface $blogPost
     * @param $privilege
     * @return bool
     */
    public function assert(Zend_Acl $acl, Zend_Acl_Role_Interface $user = null, Zend_Acl_Resource_Interface $blogPost = null, $privilege = null)
    {
    	echo ' == Checking the assertion ==' . PHP_EOL; // only here for the purposes of article

        if (!$user instanceof User) {
            throw new InvalidArgumentException(__CLASS__ . '::' . __METHOD__ . ' expects the role to be an instance of User');
        }

        if (!$blogPost instanceof BlogPost) {
            throw new InvalidArgumentException(__CLASS__ . '::' . __METHOD__ . ' expects the resource to be an instance of BlogPost');
        }

        // if role is publisher, he can always modify a post
        if ($user-&gt;getRoleId() == 'publisher') {
        	return true;
        }

        // check to ensure that everyone else is only modifying their own post
        if ($user-&gt;id != null &amp;&amp; $blogPost-&gt;ownerUserId == $user-&gt;id) {
        	return true;
        } else {
        	return false;
        }
    }
}
</pre>
<p>Note: Assertions, as with ACL&#8217;s can be treated, and most likely should be treated, as application models.  As such, if you are using the Zend Framework MVC application structure, you might want to name this one similarly to <tt>Default_Model_Acl_UserCanModifyBlogPostAssertion</tt>, and would live in <tt>application/models/Acl/UserCanModifyBlogPostAssertion.php</tt>.  Likewise, the <tt>User</tt> class would actually be <tt>Default_Model_User</tt>, and <tt>BlogPost</tt> might be <tt>Default_Model_BlogPost</tt>.</p>
<p>Now that we have our models setup for our ACL to interact with, its time to define the actual ACL definition itself.  For the purposes of this exercise, we&#8217;ll not assume that the ACL itself is a model, but our consuming script below will simply interact with it.  In a Zend Framework MVC application, one might find the ACL defined as a model within your application, depending on your needs.</p>
<pre class="brush: php; title: ; notranslate">
$acl = new Zend_Acl();

// setup the various roles in our system
$acl-&gt;addRole('guest');
$acl-&gt;addRole('contributor', 'guest');
$acl-&gt;addRole('publisher', 'contributor');

// add the resources
$acl-&gt;addResource('blogPost');

// add privileges to roles and resource combiniations
$acl-&gt;allow('guest', 'blogPost', 'view');
$acl-&gt;allow('contributor', 'blogPost', 'contribute');
$acl-&gt;allow('contributor', 'blogPost', 'modify', new UserCanModifyBlogPostAssertion());
$acl-&gt;allow('publisher', 'blogPost', 'publish');
</pre>
<p>The above code has produced a fully defined ACL object, at least for the purposes of this article, that we can now start interacting with.  In the follow examples, we&#8217;ll interact with this ACL object.  The <tt>User</tt> and <tt>BlogPost</tt> objects utilize public properties for brevity and illustrative purposes, but you can assume that these object properties might be populated and persisted via Zend_Db_Table row, a web service, or some other data source persistence layer.</p>
<pre class="brush: php; title: ; notranslate">
$user = new User();
$post = new BlogPost();

// some default values
$user-&gt;id = 1;
$post-&gt;ownerUserId = 1;

/**
 * Demonstrate guest Privileges
 */
echo 'Demonstrating ' . $user-&gt;role . ' privileges' . PHP_EOL
    . '------------------------------------------'
    . PHP_EOL . PHP_EOL;

echo 'Can user (' . $user-&gt;role . ') view?' . PHP_EOL
    . ($acl-&gt;isAllowed($user, $post, 'view') ? 'yes' : 'no') . PHP_EOL
    . PHP_EOL; 

echo 'Can user (' . $user-&gt;role . ') contribute?' . PHP_EOL
    . ($acl-&gt;isAllowed($user, $post, 'contribute') ? 'yes' : 'no') . PHP_EOL
    . PHP_EOL;

echo 'Can user (' . $user-&gt;role . ') modify?' . PHP_EOL
    . ($acl-&gt;isAllowed($user, $post, 'modify') ? 'yes' : 'no') . PHP_EOL
    . PHP_EOL;

echo 'Can user (' . $user-&gt;role . ') publish?' . PHP_EOL
    . ($acl-&gt;isAllowed($user, $post, 'publish') ? 'yes' : 'no') . PHP_EOL
    . PHP_EOL;

/**
 * Demonstrate contributor Privileges
 */

$user-&gt;role = 'contributor';

echo 'Demonstrating ' . $user-&gt;role . ' privileges' . PHP_EOL
    . '------------------------------------------'
    . PHP_EOL . PHP_EOL;

echo 'Can user (' . $user-&gt;role . ') view?' . PHP_EOL
    . ($acl-&gt;isAllowed($user, $post, 'view') ? 'yes' : 'no') . PHP_EOL
    . PHP_EOL; 

echo 'Can user (' . $user-&gt;role . ') contribute?' . PHP_EOL
    . ($acl-&gt;isAllowed($user, $post, 'contribute') ? 'yes' : 'no') . PHP_EOL
    . PHP_EOL;

$post-&gt;ownerUserId = 5;

// the following two examples should demonstrate the assertion being checked

echo 'Can user (' . $user-&gt;role . ') modify someone elses blogPost?' . PHP_EOL
    . ($acl-&gt;isAllowed($user, $post, 'modify') ? 'yes' : 'no') . PHP_EOL
    . PHP_EOL;

$post-&gt;ownerUserId = 1;

echo 'Can user (' . $user-&gt;role . ') modify own blogPost?' . PHP_EOL
    . ($acl-&gt;isAllowed($user, $post, 'modify') ? 'yes' : 'no') . PHP_EOL
    . PHP_EOL;

echo 'Can user (' . $user-&gt;role . ') publish?' . PHP_EOL
    . ($acl-&gt;isAllowed($user, $post, 'publish') ? 'yes' : 'no') . PHP_EOL
    . PHP_EOL;

/**
 * Demonstrate publisher Privileges
 */

$user-&gt;role = 'publisher';

echo 'Demonstrating ' . $user-&gt;role . ' privileges' . PHP_EOL
    . '------------------------------------------'
    . PHP_EOL . PHP_EOL;

echo 'Can user (' . $user-&gt;role . ') view?' . PHP_EOL
    . ($acl-&gt;isAllowed($user, $post, 'view') ? 'yes' : 'no') . PHP_EOL
    . PHP_EOL; 

echo 'Can user (' . $user-&gt;role . ') contribute?' . PHP_EOL
    . ($acl-&gt;isAllowed($user, $post, 'contribute') ? 'yes' : 'no') . PHP_EOL
    . PHP_EOL;

$post-&gt;ownerUserId = 5;

echo 'Can user (' . $user-&gt;role . ') modify someone elses blogPost?' . PHP_EOL
    . ($acl-&gt;isAllowed($user, $post, 'modify') ? 'yes' : 'no') . PHP_EOL
    . PHP_EOL;

$post-&gt;ownerUserId = 1;

echo 'Can user (' . $user-&gt;role . ') modify own blogPost?' . PHP_EOL
    . ($acl-&gt;isAllowed($user, $post, 'modify') ? 'yes' : 'no') . PHP_EOL
    . PHP_EOL;

echo 'Can user (' . $user-&gt;role . ') publish?' . PHP_EOL
    . ($acl-&gt;isAllowed($user, $post, 'publish') ? 'yes' : 'no') . PHP_EOL
    . PHP_EOL;
</pre>
<p>Once you have all of that in place, you can see a the run of such a script would produce these results:</p>
<pre class="brush: plain; title: ; notranslate">
/home/ralph/test-script/$ php acl-inheritance.php

Demonstrating guest privileges
------------------------------------------

Can user (guest) view?
yes

Can user (guest) contribute?
no

Can user (guest) modify?
no

Can user (guest) publish?
no

Demonstrating contributor privileges
------------------------------------------

Can user (contributor) view?
yes

Can user (contributor) contribute?
yes

 == Checking the assertion ==
Can user (contributor) modify someone elses blogPost?
no

 == Checking the assertion ==
Can user (contributor) modify own blogPost?
yes

Can user (contributor) publish?
no

Demonstrating publisher privileges
------------------------------------------

Can user (publisher) view?
yes

Can user (publisher) contribute?
yes

 == Checking the assertion ==
Can user (publisher) modify someone elses blogPost?
yes

 == Checking the assertion ==
Can user (publisher) modify own blogPost?
yes

Can user (publisher) publish?
yes
</pre>
<h3>Conclusion</h3>
<p>Zend_Acl can now be used to make concise, dynamic and expressive ACL systems.  The assertion system that is in place in <tt>Zend_Acl</tt> can be leveraged in ways never seen before out of the box.  While the User/BlogPost example is on the simple side, you can use this article to start thinking about the different ways such a system can be leveraged in your own projects where dynamic assertions would simplify controller or model code that is already in place.</p>
<div class="shr-publisher-34"></div><!-- Start Shareaholic LikeButtonSetBottom --><!-- End Shareaholic LikeButtonSetBottom -->]]></content:encoded>
			<wfw:commentRss>http://ralphschindler.com/2009/08/13/dynamic-assertions-for-zend_acl-in-zf/feed</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Database Abstraction Layers Must Live!</title>
		<link>http://ralphschindler.com/2009/07/15/database-abstraction-layers-must-live</link>
		<comments>http://ralphschindler.com/2009/07/15/database-abstraction-layers-must-live#comments</comments>
		<pubDate>Wed, 15 Jul 2009 17:46:22 +0000</pubDate>
		<dc:creator>Ralph Schindler</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Software Architecture]]></category>
		<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[Zend_Db]]></category>

		<guid isPermaLink="false">http://ralphschindler.com/?p=26</guid>
		<description><![CDATA[I come preaching true hope, against the fallacies. I&#8217;ve heard the arguments for and against database abstraction layers (DALs) time and time again. I must say first, I agree with them all, both sides, equally. Interestingly, I can put the vocal proponents of each side of the argument in one of two boxes: a programmer [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop --><!-- End Shareaholic LikeButtonSetTop --><p>I come preaching true hope, <a href="http://jeremy.zawodny.com/blog/archives/002194.html">against the fallacies</a>.</p>
<p>I&#8217;ve heard the arguments for and against <a href="http://en.wikipedia.org/wiki/Database_abstraction_layer">database abstraction layers (DALs)</a> time and time again.  I must say first, I agree with them all, both sides, equally.  Interestingly, I can put the vocal proponents of each side of the argument in one of two boxes: a <em>programmer guy</em> box, or a <em>database guy</em> box.  For some unknown reason though, they never seem to see eye to eye.</p>
<p>Honestly though, I like to put myself in the middle of that argument.  I see both sides.  I think fine tuning an application&#8217;s core business with vendor specific features is tremendously important, after all, that is why there are so many competing database vendors.  Generally speaking of database driven projects, I feel like planning to use a specific vendor up front, knowing its pro&#8217;s and con&#8217;s, and tailoring an application to the chosen database&#8217;s strengths can only help in the long run.  Also, I feel that building a <em>database model first</em> before any code, offers many performance and scalability advantages than does <em>code first</em> development.</p>
<p>That said, I also see value in using a database as a simple data-store when the actual database is not a key component of the overall application.  That&#8217;s right, it is completely valid to say that the data-storage &amp; database component of an application sometimes is not the key component; a database guy probably will never agree with you there.  Just as there are programmers who swear by this <em>code first, database later</em> mantra, there are database developers that will swear by the <em>database first, code later</em> mantra.</p>
<p>The fact is, each project is unique.  It&#8217;s this uniqueness of projects and their execution that ultimately shapes the perspectives of developers as well as the tools they write and consume.  To say that one mantra is clearly a better choice over another is simply being ignorant.</p>
<h3>The Use Case of Abstraction Layers</h3>
<p>To be honest, I don&#8217;t really buy the &#8220;I might switch database vendors at some point&#8221; argument either, as <a href="http://jeremy.zawodny.com/">Jeremy Zawodny</a> points out.  For larger projects (on the scale of the facebooks, the twitters, etc), switching the database underneath after a project has been in production is a monumental task- regardless if you have an abstraction layer or not.  Chances are, you used some of the database specific features, not to mention, you now have a large set of mission critical <em>data</em> that also has to be ported.  Long story short, its never as easy as swapping the abstraction layers database adapter out.</p>
<p>What I will buy though, is there are some problems that fall in thicker end of the <a href="http://en.wikipedia.org/wiki/Pareto_principle">Pareto Principle</a> that can be solved with a database abstraction layer.  For the uninitiated, the Pareto Principle is effectively the 80/20 rule.  In software use cases, when applying this term- the 80% use case is the majority of use cases.  These use cases are generally <em>not that interesting</em> in terms of database interaction.  To give it a label, we can call these the <a href="http://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a>, BREAD, or  &lt;&lt;insert your favorite terminology here&gt;&gt; operations.  That is not to say that these operations are not important, but they are not special.  In fact, they are so un-special, that we can just about apply a standard query syntax <a href="http://en.wikipedia.org/wiki/SQL-92">(SQL 92)</a> to them, and expect that the query is both portable between databases and common across applications that wish to use them.</p>
<p>This is where database abstraction fits in.  As a developer, you&#8217;ll come across this problem time and time again.  A large portion of an application are CRUD screens and the smaller more interesting part of your application is your reporting screens.  With an abstraction layer, we are able to code against both a unified API as well as have a layer that will produce consistent and vendor compatible queries.  This allows us to build more specialized <a href="http://en.wikipedia.org/wiki/Data_access_layer">data access layers</a> (patterns) for multiple database vendors with great ease.  You want <a href="http://martinfowler.com/eaaCatalog/tableDataGateway.html">Table Gateway</a>- done, you want <a href="http://martinfowler.com/eaaCatalog/rowDataGateway.html">Row Gateway</a>- done, you want <a href="http://martinfowler.com/eaaCatalog/activeRecord.html">Active Record</a>- done.   Each can be implemented to tackle the 80% part of the 80/20 rule when applied to the database centric business code of an application.</p>
<h3>The Slow Path &amp; The Fast Path</h3>
<p>When I talk about this 80/20 rule in terms of the applications we write, I like to further refine the terminology so that it easier to visualize.  The most prominent terms that helps developers visualize the 80/20 rule in their application is the <strong>slow path</strong> of your application, and the <strong>fast path</strong> of your application.  Each of these terms has a set of characteristics that set each apart from one another:</p>
<h4>Slow Path:</h4>
<ul>
<li>Performance is not of primary importance</li>
<li>Has an interactive nature</li>
<li>Validation and verification of data are of high priority</li>
<li>Application to data-store interactions are fairly trivial</li>
<li>Does not comprise applications core business logic</li>
</ul>
<h4>Fast Path:</h4>
<ul>
<li>Performance is of importance</li>
<li>Limited interactive nature, information flow is fairly static (non-interactive)</li>
<li>Flow of information consist of already verified and validated data (originates from the databsae)</li>
<li>Application to data-store interaction can become complex (JOINs, SUB-SELECTS, VIEWS)</li>
<li>Is the core business of the application</li>
</ul>
<p>To get a better understanding of how the terms are applied, lets look at a typical web application.  Generally speaking, there are a few web based forms that users interact with.  These forms are the entry point of a code path that does <em>not</em> get a lot of throughput.  This is generally because forms are submitted by people, and people can only type and submit forms so fast.  In addition to this being a less traveled code path, it also has a few checks along the way- validation of data, and verification of data.  Typically, the problems of verification and validation of data are not too unique to the application being executed.  In fact, the web forms, validation and verification problems have been solved over and over again by various libraries.</p>
<p>On the other side of the equation, there is the aggregation and merging of the stored data (which inevitably came from the aforementioned web forms.)  Since the unique aggregation and processing of this data is the core aspect of business of said application, it stands to reason that this code path will be more well traveled by users.  This, is the fast path.  The problems solved in this code path are generally unique and since they are unique, it&#8217;s hard to find an off the shelf solution to these problems.</p>
<p>Since this is where the money is to be made, it also stands to reason that developers should concentrate their efforts in the fast path of their application.  This means they should solve the slow path problems of their application with existing tried and tested solutions- this includes generic forms solutions, validation and verification libraries and yes, database abstraction layers.</p>
<h3>Getting Cozy With Zend_Db, a Database Abstraction Layer</h3>
<p>Not that we&#8217;ve made a use case for DAL&#8217;s, what would one look like?  Well, I&#8217;ll use Zend Frameworks Zend_Db as my use case.</p>
<p>The connection code:</p>
<pre class="brush: php; title: ; notranslate">
$dbAdapter = Zend_Db::factory(array(
    'adapter' =&gt; 'Pdo_Mysql', // could be Pdo_Sqlite, Mysqli, Pdo_Mysql, Db2, or even Oracle
    'params' =&gt; array(
        'username' =&gt; 'test_user',
        'password' =&gt; 'test_pwd',
        'dbname' =&gt; 'test'
        )
    ));
</pre>
<p>You&#8217;ll note that since this factory takes a standardized array, it makes it trivial to swap out various connection information for different adapters.</p>
<p>Simple queries:</p>
<pre class="brush: php; title: ; notranslate">
$data = array(
    'name'        =&gt; 'Remember the Milk',
    'description' =&gt; '2% Milk'
    'due_on'      =&gt; '2009-07-15',
    );
$dbAdapter-&gt;insert('todo_list', $data); // insert that data

// or
$lastInsertId = $dbAdapter-&gt;lastInsertId('todo_list');
$dbAdapter-&gt;update('todo_list', array('completed' =&gt; 'YES'), 'id = ' . $lastInsertId);

$dbAdapter-&gt;delete('todo_list', 'id = ' . $lastInsertId);
</pre>
<p>Here you&#8217;ll notice the generic and abstracted nature of this API.  Since there are several tasks in database interaction that are consistent across the board, those such as INSERT, UPDATE and DELETE, it makes sense that we can create a generic API for handling such interactions.  These interactions (INSERT, UPDATE and DELETE) represent the mutation methods of a database and as such, represent the most predominant way of getting data into a system.</p>
<p>For all intents and purposes though, simple SELECTs are fairly standardized too.  They are standardized enough as to compliment the INSERT, UPDATE, and DELETE abstractions so that we can find actual rows to do these mutation operations.</p>
<p>Now that we have a simple and consistent API for doing simple SELECTs, INSERTs, UPDATEs, and DELETEs; we can implement something a little more interesting: the <a href="http://framework.zend.com/manual/en/zend.db.table.html">table &amp; row gateway</a>:</p>
<pre class="brush: php; title: ; notranslate">
Zend_Db_Table_Abstract::setDefaultAdapter($dbAdapter);
$userTable = new Zend_Db_Table('user'); // ZF 1.9 feature
$userRow = $table-&gt;find(5); // find user by id 5 (primary key);
echo $userRow-&gt;username;
</pre>
<p>Immediately, you should see the inherent value in the above example.  Rudimentary and common tasks can now be handled with a consistent and simple API.  But what happens when you&#8217;ve started using this DAL, and you want to use a vendor specific feature?  Well..</p>
<pre class="brush: php; title: ; notranslate">
// assuming what you want is really REPLACE or INSERT IGNORE from mysql
$dbAdapter-&gt;query('INSERT IGNORE INTO configuration (name, value) VALUES (?, ?)', array($name, $value));

// OR
$dbAdapter-&gt;query('REPLACE INTO configuration (name, value) VALUES (?, ?)', array($name, $value));
</pre>
<p>As you can see, the query method of our database adapter will allow us to pass custom SQL into the database thus taking advantage of vendor specific features.</p>
<p>What if you want to combine both paradigms for ultimate flexibility?</p>
<pre class="brush: php; title: ; notranslate">

// assuming Zend_Db_Table_Row, with a FriendshipReference rule
$friendRowset = $currentUserRow-&gt;findDependentRowset('User', 'FriendshipReference');

// collect friend id's
foreach ($friendRowset as $friendRow) {
    $friendIds[] = $friendRow-&gt;related_user_id;
}

$inClause = ' IN (' . implode(',', $friendIds) . ')';

$select = $dbAdapter-&gt;select();
$select
    -&gt;from('user', array(
        'user_id',
        'related_user_id',
        'became_friends_on'
        ))
    -&gt;where('user_id ' . $inClause);

// interact with driver directly
$mysqli = $dbAdapter-&gt;getConnection();
$mysqli-&gt;query('CREATE TEMPORARY TABLE friend ('
        . ' `user_id` int(11) NOT NULL,'
        . ' `related_user_id` int(11) NOT NULL,'
        . ' `became_friends_on` DATE NOT NULL'
        . ' ) ENGINE=MEMORY;'
    );
$mysqli-&gt;query('INSERT INTO friend ' . (string) $select);

// query new friend view
$friendTable = new Zend_Db_Table('friend');
$rows = $friendTable-&gt;fetchAll(
    'became_friends_on &gt; DATE_SUB(CURDATE(), INTERVAL 6 MONTH)',
    'became_friends_on'
    );
</pre>
<p>While that above example is &#8220;a bit out there&#8221;, it does show that even with a DAL, if it&#8217;s flexible enough, you can code as close to or as far away from the database as you like.  Ultimately the mantra here is: lets get the job done in the most effective, efficient and sound way possible.</p>
<h3>Conclusions</h3>
<p>Simply put, a database abstraction layer is just another tool in the toolbox.  You don&#8217;t have to completely change your paradigm of programming, nor do you have to apply an all-or-none approach to using a DAL.  When applied correctly, you can build out the slow path of your application in little to no time, while leaving extra time for developing and fine-tuning the fast path of your application.  And to keep code from becoming unruly, simply apply some <a href="http://ralphschindler.com/2009/05/24/php-environments-libraries-and-applications-oh-my">best-practices code organization</a> to your project.</p>
<div class="shr-publisher-26"></div><!-- Start Shareaholic LikeButtonSetBottom --><!-- End Shareaholic LikeButtonSetBottom -->]]></content:encoded>
			<wfw:commentRss>http://ralphschindler.com/2009/07/15/database-abstraction-layers-must-live/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>PHP: Environments, Libraries, and Applications &#8211; Oh My!</title>
		<link>http://ralphschindler.com/2009/05/24/php-environments-libraries-and-applications-oh-my</link>
		<comments>http://ralphschindler.com/2009/05/24/php-environments-libraries-and-applications-oh-my#comments</comments>
		<pubDate>Sun, 24 May 2009 19:31:14 +0000</pubDate>
		<dc:creator>Ralph Schindler</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Software Architecture]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://ralphschindler.com/?p=20</guid>
		<description><![CDATA[Over the past 10 years or so, I&#8217;ve worked with many different code bases and libraries. Originally, the &#8220;libraries&#8221; were my own because in my earlier programming days, I had a bad case of &#8220;NCH&#8221; syndrome. That&#8217;s &#8220;Not Coded Here&#8221; syndrome for the uninitiated. As time had gone on, there were some solutions that I [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop --><!-- End Shareaholic LikeButtonSetTop --><p>Over the past 10 years or so, I&#8217;ve worked with many different code bases and libraries.  Originally, the &#8220;libraries&#8221; were my own because in my earlier programming days, I had a bad case of &#8220;NCH&#8221; syndrome.  That&#8217;s &#8220;Not Coded Here&#8221; syndrome for the uninitiated.  As time had gone on, there were some solutions that I needed for a simple project and did not have the time nor the patience to develop a custom library for.  That&#8217;s when I started relying on others experience and code to get me through projects.</p>
<p>The first &#8220;library&#8221; I remember using was <a href="http://px.sklar.com">px.sklar.com</a> by <a href="http://www.sklar.com">David Sklar</a>.  There were some great components in there that were worth integrating into projects, but I hesitate to call it a true library though since its both a repository of both reusable components as well as complete solutions/applications.  Moving on into the 21st century, a more &#8220;official&#8221; PHP library was being born; the PEAR project.  The first component I really started depending on for many projects was the <a href="http://pear.php.net/package/Spreadsheet_Excel_Writer">Spreadsheet_Excel_Writer</a>.  PEAR is not without issues of its own, but thats a topic for a separate article.</p>
<h2>A Little History</h2>
<p>My earliest PHP applications where fairly simple.  A PHP page that would interact with a database, and render some html.  Looking back at them, they all look like oodles of hacks and spaghetti code.  Of course this was 1999ish, so it was OK because after all, it got the job done.  As projects grew larger, so did a desire for better organization.  This new wave of applications I was writing at the time was the first divergence from <a href="http://en.wikipedia.org/wiki/Model_1">Model 1</a> applications, and came with the introduction of the second library I started using.</p>
<p><a href="http://www.smarty.net">Smarty</a> (which used to be part of the PHP Project), was a library I came to depend on in every project.  The single greatest aspect of Smarty from a code organization standpoint was that it separated scripts into &#8220;business logic&#8221; scripts and &#8220;presentation logic&#8221; scripts.  If an application was a soup of code, Smarty was the tool which divided out the presentation specific code, or what we&#8217;d call the &#8216;view&#8217; in the MVC paradigm, from the business specific code, or what we&#8217;d call the controller and model in the MVC paradigm.  This was the first step many took towards what is known in the JSP world as <a href="http://en.wikipedia.org/wiki/Model_2">Model 2</a> programming.</p>
<p>So why this history wrapped in with a little personal experience?  Well, I&#8217;d say the path I have followed is pretty typical of programmers that use scripting languages to build applications, specifically web-applications.  That said, as the technologies we&#8217;ve used evolved and grown.. we tend to move towards solutions that offer a sense of best practices, better code organization, and most importantly- reduce the time to market.</p>
<p>What does that have to do with you?  Well, I&#8217;ve seen my share of PHP centric projects come and go.  In addition to those projects, I&#8217;ve kept a watchful eye on projects in other communities such as the Ruby, Perl, Java and .NET communities.  From them, we&#8217;ve borrowed concepts, ideas and tools to create better solutions for the PHP community.  With that, I&#8217;ll continue on with explaining several of the most common facets of any PHP project.  If this seems basic at first, its actually laying the groundwork for a few more in-depth articles down the line.</p>
<h2>What is an Environment?</h2>
<p>In PHP, the environment is the set of resources, capabilities and settings for immediate use within the lifespan of any one php process.  I know thats a very general statement, but lets explore that a bit.  On most systems, you&#8217;ll find a php.ini file.  This ini file generally sets values for the php process to initialize with when it starts up.  Some of these can be modified by the SAPI (command line layer, apache layer, etc), while other can be modified during runtime via <code>set_ini</code>, and others cannot be modified at all.</p>
<p>Each time a script is executed, it first inherits these php.ini values.  This means, by default, if none have changed, a script is subject to the rules defined by the php.ini on the <em>system</em>.  If these values (php.ini system values) are out of your control, this means that the script running has an <em>ambiguous initial environment</em>.  This environment might have been defined by the system administrator or by the packager of the php distribution you are using.  </p>
<p>If you are subject to an ambiguous environment setup, there are greater the chances your application will fail upon setup or during execution.  At least one of these situations has come to plague a PHP developer at one time or another:</p>
<ul>
<li><code>display_errors</code> might be off, causing a <a href="http://www.urbandictionary.com/define.php?term=wtf%20moment">WTF moment</a> when an error arises.  </li>
<li><code>error_reporting</code> level is set to E_STRICT and the script was not written with respect to the error_reporting including this mode, thus creating 100&#8242;s of notices.  </li>
<li><code>open_basedir</code> was set and your script doesn&#8217;t have access to some resources it expects to have access to.  </li>
</ul>
<p>Those are just 3 of the more popular examples stemming from 3 different keys that can be set within a php.ini.  To put it in a bigger perspective: there are 100s of these values.  The point that needs to be most impressed is that for any given php script or php application, it should either check the environment at script startup, or in the least provide all of the environment prerequisites and assumptions the script or application makes.  The ideal solution is to supply a script that will check the environment and report at installation time if the ini values are correct.</p>
<p>One of the more interesting environment variables in PHP, much like other languages and systems, is the common path.  In PHP, the common path is called the <code>include_path</code>.  The <code>include_path</code> just might be the most important php.ini based value to any script or project.  During a PHP scripts runtime, the loading of files and components are generally checked against the paths defined within the <code>include_path</code>.  This means that any scripts or classes (effectively any PHP code) can be located and loaded with a relative path, a path that is relative to any of the paths defined in the <code>include_path</code>.</p>
<p>The <code>include_path</code> is a pretty powerful thing.  It makes it easier to bundle components and packages into &#8220;libraries&#8221;, and use them within projects.  This helps facility DRY principals by encouraging good code reuse and solid library design.  On the other hand, if you don&#8217;t properly manage your libraries that are on your include_path, this could pose some pretty significant problems down the line.  More on that later though.</p>
<p>The general rule of thumb is this: take control of the php process&#8217;s environment as much as possible to ensure consistent behavior.</p>
<h2>What is a Library?</h2>
<p>Its seems like <strong>library</strong> is a fairly generic term, but I want to add some specific meaning to it at least in terms of PHP.  A general definition of a library would effectively be a &#8220;collection of reusable code&#8221;; and that statement is true for all intents and purposes.  For the purposes of this article, I&#8217;d like to take that a little further.</p>
<p>A library is a collection of <strong>components</strong>.  While a library <em>solves a less specific general problem</em>, components <em>solve a more specific general problem</em>.  Get it yet?  </p>
<p>For demonstration purposes, I&#8217;ll use the <a href="http://framework.zend.com]">Zend Framework</a>.. since I&#8217;m a little biased towards that one.  The Zend Framework has a couple of libraries, the main one called the <a href="http://framework.zend.com/svn/framework/standard/">Standard Library</a>.  The ZF Standard Library solves a pretty general problem: &#8220;The PHP Application problem&#8221;.  As you can see, thats a fairly general (relatively speaking) problem it attempts to solve.  This library is made up of several components that solve specific problems within the &#8220;PHP Application problem.&#8221;  For example, Zend_View and Zend_Controller solve the &#8220;web application structure&#8221; problem.  Zend_Form solves the &#8220;web forms&#8221; problem.  So on and so forth.  These are problems that can be solved with tried, tested, and true solutions.  These solutions can generally be considered &#8220;<a href="http://en.wikipedia.org/wiki/Best_coding_practices">best practices</a>&#8220;.  They are solved so that you can get onto solving the even more specific problems&#8230; those inside the &#8220;application&#8221;.</p>
<p>Its worth noting that the definition of a library is also relative to the audience its targeted at.  In our above example, the Zend Framework&#8217;s intended audience is all PHP developers.  Your company, on the other hand, has a smaller target audience: its internal developers.  Since that audience is a smaller and more concise group, their needs are more specific than those of the global developer community.  That means that a company&#8217;s &#8220;library&#8221; might solve &#8220;more specific general problems&#8221; on a company wide scale.   For example, a company might have 10 applications that use a single-sign-on system.  Since those 10 applications within that company have the <em>less specific problem</em> of user sign on, that solution would be best fitted inside the company&#8217;s &#8220;library&#8221;.  </p>
<p>In general, libraries solve problems that are generic enough for the entire intended audience, and each problem solved into a component of the &#8220;library&#8221;.  Everything else goes into your &#8220;application&#8221;.</p>
<h2>What is an Application?</h2>
<p>As hinted above in the section on libraries, an application too is defined by the problem it attempts to solve.  An <strong>application</strong> is a collection of <em>business specific</em> code which solves a very specific business problem.  Again, this sounds generic, but it can be further defined and explained.</p>
<p>A <em>business problem</em> is the most specific problem that can be solved with code; this is the application.  It will be the sum of all target environments, target audiences, and target tasks that should be solved.  These business problems have a very narrow focus.  While applications can be further defined into specific areas of code, the whole of the application&#8217;s object is to solve the <em>business problem</em>.</p>
<p>Depending on how complicated the business problem is that is target of the application to solve; an application might be <strong>modular</strong>.  If an application is modular, that implies that the application&#8217;s problem area can be divided into even more specific areas of code with specific responsibilities.  Lets take a community website for example.  The site might include forums, user management, mail, calendaring and news.  Each of these respective areas of the site could be considered modules of the main application or website.  While this is a generic example, it does demonstrated a logical division of responsibility which is ultimately the point of introducing modules into an application.  Each project and business should evaluate their application and decide upfront how granular the application&#8217;s problem is, and how best to further divide it.  Doing this up front will alleviate many issues that could arise later as the code base starts to grow.</p>
<p>Beyond the modularity of an application, a further, more logical division and organization of code is generally applied.  While there are several paradigms of application organization, we&#8217;ll focus on the <a href="http://en.wikipedia.org/wiki/Model-view-controller">MVC</a> architecture (if you are not familiar with the MVC architecture it might be best to read the wikipedia article first before moving forward).  Both an applications module and a non-modular application can be organized into Models, Views, and Controllers.. the main constituents of the MVC paradigm.  Without getting to involved into what MVC is, one should know that:</p>
<ul>
<li>The <strong>model</strong> represents the code base for solving the <em>business problem</em> at hand in a UI and environment agnostic way.</li>
<li>The <strong>controller</strong> represents the code base responsible for bridging a user&#8217;s interaction with the UI to the business model, and setting up new UI.</li>
<li>The <strong>view</strong> represents the code base responsible for creating the environment specific UI.</li>
</ul>
<p>The above grouping of purposes is what is called as <em>a separation of concerns</em>.</p>
<h2>Recap</h2>
<p>Here is a recap of the terms defined within this article:</p>
<ul>
<li>An Environment is the sum of all resources, capabilities and settings that exist in a PHP process.  This generally includes what extensions and ini settings are preset for the PHP process.</li>
<li>A Library is collection of code that solves a <em>less specific problem</em> which is further defined by the libraries target audience and problem area.</li>
<li>A Component is a collection of code that solves a <em>more specific problem</em> <strong>within</strong> a library.</li>
<li>An Application is collection of code that solves a <em>specific business problem</em>.  Ideally, applications consume libraries and components to facilitate quicker and more standardized development.</li>
<li>A Module is a collection of code that solves a <em>more specific atomic problem of the larger business problem</em>.  The sum of all modules within an application attempt the solve the larger <em>business problem</em>.</li>
<li>MVC is a way to group code within both a module and application into a code base that facilitate a better <em>separation of concerns</em>.</li>
</ul>
<div class="shr-publisher-20"></div><!-- Start Shareaholic LikeButtonSetBottom --><!-- End Shareaholic LikeButtonSetBottom -->]]></content:encoded>
			<wfw:commentRss>http://ralphschindler.com/2009/05/24/php-environments-libraries-and-applications-oh-my/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>PHPAustin Meetup Slides &#8211; Software Engineering In PHP</title>
		<link>http://ralphschindler.com/2009/05/15/phpaustin-meetup-slides-software-engineering-in-php</link>
		<comments>http://ralphschindler.com/2009/05/15/phpaustin-meetup-slides-software-engineering-in-php#comments</comments>
		<pubDate>Fri, 15 May 2009 17:40:00 +0000</pubDate>
		<dc:creator>Ralph Schindler</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[AustinPHP]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Software Architecture]]></category>
		<category><![CDATA[Software Engineering]]></category>

		<guid isPermaLink="false">http://ralphschindler.com/?p=9</guid>
		<description><![CDATA[On Tuesday, Josh Butts and I gave a presentation at the monthly Austin PHP Meetup titled &#8220;Software Engineering In PHP&#8221;.  Around 30 people were present and judging by the number of questions that were raised on each slide, the interest in the subject matter was fairly high.  In the end, it took around 2:15 to [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop --><!-- End Shareaholic LikeButtonSetTop --><p>On Tuesday, <a href="http://joshbutts.com">Josh Butts</a> and I gave a presentation at the monthly <a href="http://php.meetup.com/42">Austin PHP Meetup</a> titled &#8220;Software Engineering In PHP&#8221;.  Around 30 people were present and judging by the number of questions that were raised on each slide, the interest in the subject matter was fairly high.  In the end, it took around 2:15 to get through the 35 or so slides.</p>
<p>So where did this talk come from? Its the culmination of several ideas for talks I&#8217;ve had over the past several months, as well as parts taken from conversations with Josh &#8211; who covered the sections on the PHP Ecosystem and Software Development.  The general idea is to build one talk that speaks to several different audiences: the self-educated PHP Developer, the once Java/.Net now PHP Developer, the Developer in search of best practices, and the Developer who wants to become the Engineer, and the Developer who simply wants to know more about their language of choice.</p>
<p>This talk takes an &#8220;engineering first&#8221; approach to the language discussing how it fits into development world amongst the 1000&#8242;s of languages currently out there.  Each slide has several links for more extensive reading.  In fact, these slides alone could send you off into the Wikipedia black hole for days of reading.  For us, that is ultimately the goal.  Many developers do not know where to start on their path of &#8220;PHP enlightenment&#8221;, but these slides are a starting point.</p>
<p>These slides are very &#8220;Beta-ish&#8221; (in the Google sense).  I plan to revise it periodically with more code samples in PHP that help explain the concepts and terminologies in each slide.  For any suggestion and/or criticisms, please comment below.</p>
<p style="text-align: center;"><iframe src="http://www.slideshare.net/slideshow/embed_code/1430556" width="450" height="375" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe><br/><br/></p>
<div class="shr-publisher-9"></div><!-- Start Shareaholic LikeButtonSetBottom --><!-- End Shareaholic LikeButtonSetBottom -->]]></content:encoded>
			<wfw:commentRss>http://ralphschindler.com/2009/05/15/phpaustin-meetup-slides-software-engineering-in-php/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

