<?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; Software Architecture</title>
	<atom:link href="http://ralphschindler.com/tag/software-architecture/feed" rel="self" type="application/rss+xml" />
	<link>http://ralphschindler.com</link>
	<description>Ralph Schindler</description>
	<lastBuildDate>Wed, 12 May 2010 21:58:33 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<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 [...]]]></description>
			<content:encoded><![CDATA[<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>
]]></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>9</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 [...]]]></description>
			<content:encoded><![CDATA[<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;">
$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;">
$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;">
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;">
// 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;">

// 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>
]]></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 [...]]]></description>
			<content:encoded><![CDATA[<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&#8217;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>
]]></content:encoded>
			<wfw:commentRss>http://ralphschindler.com/2009/05/24/php-environments-libraries-and-applications-oh-my/feed</wfw:commentRss>
		<slash:comments>5</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[<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&#8217;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;"><object width="450" height="369"><param name="movie" value="http://static.slideshare.net/swf/ssplayer2.swf?doc=softwareengineeringinphp-v1-090513142550-phpapp02"/><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slideshare.net/swf/ssplayer2.swf?doc=softwareengineeringinphp-v1-090513142550-phpapp02"  type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="450" height="369"></embed></object></p>
]]></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>
