<?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; Development</title>
	<atom:link href="http://ralphschindler.com/tag/development/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>Compiling Gearman (or anything) for Zend Server CE on Snow Leopard</title>
		<link>http://ralphschindler.com/2010/05/12/compiling-gearman-or-anything-for-zend-server-ce-on-snow-leopard</link>
		<comments>http://ralphschindler.com/2010/05/12/compiling-gearman-or-anything-for-zend-server-ce-on-snow-leopard#comments</comments>
		<pubDate>Wed, 12 May 2010 21:58:33 +0000</pubDate>
		<dc:creator>Ralph Schindler</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://ralphschindler.com/?p=98</guid>
		<description><![CDATA[The first thing you need to know about Mac OS.X Snow Leopard all Mac&#8217;s and Macbook Pro&#8217;s is that this hardware is 64 bit capable.  This may not mean you are running a 64 bit kernel, it simply means that the operating system is capable of executing x86 64bit executables.  We won&#8217;t go [...]]]></description>
			<content:encoded><![CDATA[<p>The first thing you need to know about Mac OS.X Snow Leopard all Mac&#8217;s and Macbook Pro&#8217;s is that this hardware is 64 bit capable.  This may not mean you are running a 64 bit kernel, it simply means that the operating system is capable of executing x86 64bit executables.  We won&#8217;t go into the details of kernel architecture, you can read more about that <a href="http://www.osnews.com/story/22009/Snow_Leopard_Seeds_Use_32bit_Kernel_Drivers_by_Default">here</a>.</p>
<p>What is important though is that both x86_64 and i386 based executables can run on snow leopard.  What is not uncommon on OS.X is to have executables (and libraries) that have multiple architectures compiled in.  To see what architectures are inside a particular file, run something like this:</p>
<pre class="brush: plain; highlight: [1,7];">
    /usr/local# file /usr/bin/php
    /usr/bin/php: Mach-O universal binary with 3 architectures
    /usr/bin/php (for architecture x86_64): Mach-O 64-bit executable x86_64
    /usr/bin/php (for architecture i386):   Mach-O executable i386
    /usr/bin/php (for architecture ppc7400):        Mach-O executable ppc

    /usr/local# file /usr/local/zend/apache2/bin/httpd
    /usr/local/zend/apache2/bin/httpd: Mach-O executable i386
</pre>
<p>This means that PHP (supplied by apple), has been compiled with 3 architectures inside.  What does that mean? It means there is basically 3 versions on PHP compiled into a single binary, and that when it is loaded into memory, only one particular version will be used at a time.  To demonstrate, lets take a pretty common difference between 32bit and 64bit architectures: integer size.  We know that 64 bit integer space is larger than that of the 32bit space.  The following demo will show running different architectures from the same binary:</p>
<pre class="brush: plain; highlight: [1,4];">
    /usr/local# arch -arch x86_64 /usr/bin/php -nr 'echo PHP_INT_MAX;'
    9223372036854775807

    /usr/local# arch -arch i386 /usr/bin/php -nr 'echo PHP_INT_MAX;'
    2147483647
</pre>
<p>We know we are running same command though different architectures since we know PHP has different max integer sizes.</p>
<p>The next important thing to understand is the nature of the PHP stack.  PHP is generally regarded as a glue language.  That might mean several things to different people, but we will be looking strictly at this statement in the purest technical sense.  PHP is made of the core language and features, but also a rich set of extensions.  These extensions are typically written in C, and have interfaced with the C layer PHPAPI.  Most of the really useful extensions are linked against libraries on your system, for example the openssl set of functions are not actually implemented in PHP&#8217;s source code, the openssl extension is simple a wrapper that calls out to libssl.so (or .dylib on mac, .dll on windows).  This is what is meant by PHP being a glue language/platform.</p>
<p>Since PHP relies on existing compiled libraries, you further have to understand how things are linked and compiled.  There are generally two options here: linking dynamically, or statically compiling.  Either way, one thing remains true: <em>you cannot mix architectures</em>.  This means that if your apache/mod_php and/or php binary are only i386, then <em>all</em> of the libraries on your system that will be used must contain the i386 architecture.  Likewise, apache/mod_php and/or php binary are only x86_64, then <em>all</em> of your libraries must contain the x86_64 architecture.  Failing to have this, you will get a message like this for example:</p>
<pre class="brush: plain;">
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/local/zend/lib/php_extensions/gearman.so' - dlopen(/usr/local/zend/lib/php_extensions/gearman.so, 9): no suitable image found.  Did find:
/usr/local/zend/lib/php_extensions/gearman.so: mach-o, but wrong architecture in Unknown on line 0
</pre>
<p>Now that we understand that executables and libraries can have multiple architectures, let&#8217;s get to the task at hand: making sure new extensions can run with <a href="http://www.zend.com/en/products/server-ce/">Zend Server CE</a>.</p>
<p>Zend Server CE for Mac (as of this writing), comes compiled as an i386 executable only.  This includes the PHP binary, php library, and apache binaries that come shipped with ZSCE.  While ZSCE works great out the box with all the provided extensions, you might find that you want some additional 3rd party PHP extensions compiled/linked into this stack.  That&#8217;s where things get a little confusing, and in this post, we&#8217;ll look at how to install the <a href="http://pecl.php.net/package/gearman">gearman extension</a>.</p>
<p>PHP Extensions are basically wrappers around existing libraries, so generally, these extensions require the base library to already be on the system.  In our case, we need &#8220;libgearman&#8221; compiled and on our system for us to be able to compile and use the PHP Gearman Extension.</p>
<p>At this point, I would generally instruct you to compile Gearman with multiple architectures and install (&#8211;prefix=/usr/local).  (Note: to compile for multiple architectures, simply do the following):</p>
<pre class="brush: plain; highlight: [1];">
    export CFLAGS='-arch i386 -arch x86_64'
</pre>
<p>In the particular case of Gearman, this will not work as the Gearman makefile utilizes flags that are not compatible with multiple architecture targets.  As such, we go to plan B.</p>
<p>Plan B is something I generally do to keep my system clean: statically building libraries.  I have a personal rule of not keeping i386 only libraries installed in common places like /usr/lib or /usr/local/lib, in this case /usr/local/lib/libgearman.dylib.  Since this is the case, I&#8217;ll build Gearman statically, compile it into the PHP Gearman Extension, and this will allow me to remove the temporary Gearman installation which will have to be i386 only.</p>
<pre class="brush: plain; highlight: [4,11,12,13,17,21,23,26,27,28,34,35,36,37,42,43,44,50,56];">
    # check to ensure we have a multi-arch libevent (if not go create it as
    # normal with CFLAGS=&quot;-arch i386 -arch x86_64&quot; and install to /usr/local)

    /usr/local/src/gearmand-0.13# file /usr/local/lib/libevent.dylib
        /usr/local/lib/libevent.dylib: Mach-O universal binary with 2 architectures
        /usr/local/lib/libevent.dylib (for architecture i386):  Mach-O dynamically linked shared library i386
        /usr/local/lib/libevent.dylib (for architecture x86_64):        Mach-O 64-bit dynamically linked shared library x86_64

    # next compile gearman to a temp location

    /usr/local/src/gearmand-0.13# export &quot;CFLAGS=-arch i386&quot;
    /usr/local/src/gearmand-0.13# ./configure --disable-shared --prefix=/usr/local/gearman-tmp
    /usr/local/src/gearmand-0.13# make &amp;&amp; make install
        [gearman installed now, this should only have static files]

    # ensure we only have a .a library file for gearman
    /usr/local/src/gearmand-0.13# ls /usr/local/gearman-tmp/lib/
        libgearman.a    libgearman.la   pkgconfig

    # make sure zend/bin is first on your PATH
    /usr/local/zend/tmp# echo $PATH
        /usr/local/zend/bin:/var/root/.bin:/usr/local/git/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
    /usr/local/zend/tmp# which phpize
        /usr/local/zend/bin/phpize

    # next, go to our zend server location, and pull down gearman extension
    /usr/local/src/gearmand-0.13# cd /usr/local/zend/tmp/
    /usr/local/zend/tmp# pecl download gearman-beta
        downloading gearman-0.7.0.tgz ...
        Starting to download gearman-0.7.0.tgz (29,258 bytes)
        .........done: 29,258 bytes
    File /usr/local/zend/tmp/gearman-0.7.0.tgz downloaded

    # next, unpack, phpize, and statically compile
    /usr/local/zend/tmp# tar zxf gearman-0.7.0.tgz
    /usr/local/zend/tmp# cd gearman-0.7.0
    /usr/local/zend/tmp/gearman-0.7.0# phpize
        Configuring for:
        PHP Api Version:         20090626
        Zend Module Api No:      20090626
        Zend Extension Api No:   220090626
    /usr/local/zend/tmp/gearman-0.7.0# ./configure --with-gearman=/usr/local/gearman-tmp/ --disable-shared
    /usr/local/zend/tmp/gearman-0.7.0# make
    /usr/local/zend/tmp/gearman-0.7.0# make install
        Installing shared extensions:     /usr/local/zend/lib/php_extensions/

    # Now go add extension=gearman.so to your php.ini file inside /usr/local/zend/etc/php.ini

    # Now go check that php will have gearman support
    /usr/local/zend# php -i | grep gearman
        gearman
        gearman support =&gt; enabled
        libgearman version =&gt; 0.13

    # Since we statically compiled it, we can remove our temp install of gearman
    /usr/local/zend# rm -Rf /usr/local/gearman-tmp/
</pre>
<p>At this point, you now have a 3rd party PECL extension that is compiled and working with ZSCE on Mac OS.X.</p>
]]></content:encoded>
			<wfw:commentRss>http://ralphschindler.com/2010/05/12/compiling-gearman-or-anything-for-zend-server-ce-on-snow-leopard/feed</wfw:commentRss>
		<slash:comments>3</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, [...]]]></description>
			<content:encoded><![CDATA[<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;">
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>&#8217;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;">
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;">
$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;">
$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;">
/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>
]]></content:encoded>
			<wfw:commentRss>http://ralphschindler.com/2009/08/13/dynamic-assertions-for-zend_acl-in-zf/feed</wfw:commentRss>
		<slash:comments>12</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>
