<?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>php&#124;architect - The site for PHP professionals &#187; code</title>
	<atom:link href="http://www.phparch.com/tag/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.phparch.com</link>
	<description>Just another WordPress site</description>
	<lastBuildDate>Fri, 10 Feb 2012 15:11:29 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>PHP 5.3 namespaces for the rest of us</title>
		<link>http://www.phparch.com/2010/03/namespaces-in-php/</link>
		<comments>http://www.phparch.com/2010/03/namespaces-in-php/#comments</comments>
		<pubDate>Mon, 29 Mar 2010 11:30:14 +0000</pubDate>
		<dc:creator>Marco Tabini</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[namespaces]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[php 5.3]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.phparch.com/?p=4601</guid>
		<description><![CDATA[The introduction of namespaces in PHP 5.3 is bringing a new concept in the PHP world, and knowing how to leverage the new features is important for writing concise and readable code.]]></description>
			<content:encoded><![CDATA[<p><a href="http://beta.phparch.com/wp-content/uploads/2010/03/php1.gif"><img class="alignleft size-full wp-image-4602" title="php" src="http://beta.phparch.com/wp-content/uploads/2010/03/php1.gif" alt="" width="120" height="67" /></a>According to the official documentation, PHP namespaces have been designed to prevent name collisions between classes from different packages and to avoid the use of very long names in the code to refer to classes or functions—nobody really wants to have to deal with something called <code>Zend_Db_Adapter_Mysqli</code> or <code>PHPUnit_Framework_Constraint_IsInstanceOf</code>, after all. This means that namespaces help a developer write code that is both more concise and clearer—a direction which is always an improvement towards expressiveness.</p>
<p>Within the PHP implementation of namespaces, these names will be ideally refactored to <code>Zend\Db\Adapter\Mysqli</code> and <code>PHPUnit\Framework\Constraint\IsInstanceOf</code>, where <code>\</code> is the namespace separator. In the codebase, however, there will typically be very few references to these classes with their <em>fully qualified name</em>, because it is possible to import entire namespaces in a script and then use the class names directly, making the code easier to follow and unambiguous to write.</p>
<p>In fact, the definition of a namespace class itself does not contain its fully qualified name. For example, this would be the source file of an hypothethical <code>MyLibrary\TypeOfComponents\MyClass</code> class:</p>
<pre lang="php">&lt;?PHP
namespace MyLibrary\TypeOfComponents;

class MyClass
{
    // ...
}</pre>
<p>The convention when writing namespace-enabled code is that of creating a folder structure that reflects the individual components of a namespace (for example, <code>MyClass</code> would be in the <code>MyLibrary/TypeOfComponents</code> directory. This helps <a title="Standard autoloading proposal for major PHP frameworks" href="http://groups.google.com/group/php-standards/web/psr-0-final-proposal">standardizing the autoloading process</a>.</p>
<h2>How namespaces work</h2>
<p>Namespaced name resolution has been retrofitted in PHP 5.3 by inserting a processing mechanism at compile time. All the references to classes and functions in a namespaced source file are parsed <em>before</em> the actual execution of the PHP script and substituted with fully qualified names.</p>
<p>But <a title="Namespace resolution rules from the PHP manual" href="http://it.php.net/manual/en/language.namespaces.rules.php">what rules</a> does the name resolution process follow? You can better understand this process with a filesystem metaphor:</p>
<ul>
<li>Every name that does not start with a backslash is interpreted as a relative reference (path) from the current namespace (directory). For example, in the source code above, <code>MyClass</code> would refer to <code>MyLibrary\TypeOfComponent\MyOtherClass</code> with the unqualified name <code>MyOtherClass</code>. It can also refer to <code>MyLibrary\TypeOfComponents\SubNamespace\ACollaborator</code> with the qualified name <code>SubNamespace\ACollaborator</code>.</li>
<li>Names that start with a backslash are always relative to the global namespace (to the root directory), and are always resolved to the literal specified value. For example, <code>\PHPUnit\Framework\TestCase</code> class is resolved to the fully qualified name of <code>PHPUnit\Framework\TestCase</code>.</li>
</ul>
<p>Note that the name resolution process examples above are limited to classes, but the same concepts apply to methods.</p>
<p>Pre-PHP 5.3 code will not, of course, have any namespace defined in it and will continue to work as before, residing in the global namespace because there are no <code>namespace</code> keywords.</p>
<h2>Fallback</h2>
<p>There is however an exception to the resolution process I have just described: constants and functions that are defined in the global namespace—including all built-in PHP functions like <code>is_array()</code> and <code>strlen()</code>.</p>
<p>If we had to refer to each function using its fully-qualified name and prefix them with a backslash every time we need to use them, our code would pretty soon become an unreadable jumble of symbols. For example, you&#8217;d have to write <code>\strlen()</code> in all namespaced code, because the <code>strlen()</code> function is defined in the global namespace, and not in the current one.</p>
<p>Luckily, function and constant name resolution falls back to the global namespace when they are not found in a more specific one that is currently available. Thus, you can call <code>strlen()</code> from namespaced code without using a leading backslash—as long, of course, as you do not have a <code>strlen()</code> function defined in the current namespace that will <em>shadow</em> the global one.</p>
<p>This fallback rule does not apply to classes and interfaces: <a title="Standard Php Library documentation" href="http://www.php.net/~helly/php/ext/spl/">SPL</a>&#8216;s constructs such as <code>Iterator</code> and <code>ArrayObject</code>, for example, must be written as <code>\Iterator</code> and <code>\ArrayObject</code> in namespaced code, or they won&#8217;t work.</p>
<p>You can think of this rule as having these functions defined in your <code>PATH</code> environment variable: no one refers to the <code>ls</code> (<em>dir</em> at a Windows shell prompt) command as <code>/bin/ls</code>.</p>
<h2>Importing classes</h2>
<p>Being able to refer to classes in the current namespace without their fully qualified name is a good improvement over the long class names we had to deal with before namespaces, but we can expand the name aliasing further.</p>
<p><em>Import statements</em> that create aliases to fully qualified names can be inserted after the <code>namespace</code> keyword, which is always the first language construct at the beginning of the file when present. These aliases are local to the file. Consider this example:</p>
<pre lang="php">&lt;?PHP
namespace MyLibrary;

use ExternalLibrary\Filter\Int as IntFilter;
use ExternalLibrary\Filter\NotEmptyString;</pre>
<p>In a source file with these <code>use</code> statements, you can refer to the <code>IntFilter</code> and <code>NotEmptyString</code> classes without any syntax noise. If an explicit alias is not defined, the base name (<code>NotEmptyString</code>) is used as a default value, and it is usually sufficient.</p>
<p>Again, we can extend the filesystem metaphor to cover the import functionality. Aliases can be compared to symlinks from the current directory to an absolute path: you are able to refer to the symlink with a short base name instead of using a long absolute path.</p>
<p>Importing class and function names makes namespace very efficient to employ. The fully qualified name of an external class is hidden from the source code and extracted at the top of the file: if it changes, it is easy enough to update a single instruction instead of refactoring large areas of code. Moreover, with this approach the external dependencies are explicitly listed in a single point for every source file.</p>
<h2>Dynamic features</h2>
<p>Name resolution happens at compile time; therefore, every time a class is referenced dynamically, such as when using a variable variable or passing a parameter to (for example) <code>class_exists()</code>, you must be a fully qualified class name:</p>
<pre lang="php">$instance = new $class();
$boolean = class_exists($class);
$boolean = $instance instanceof $class;</pre>
<p>In these use cases, by the time the code is executed, the resolution process will have already occurred and, obviously, the compiler will have no way of telling whether <code>$class</code> contains a class reference that must be resolved; therefore you must make sure that it contains a full-qualified class name in order for things to work properly.</p>
<p>Despite their simplicity, some of the less-obvious aspects of namespaces can be difficult to understand when you&#8217;re first starting out. If you have any other doubts, you can read the <a title="Namespaces FAQ from php.net" href="http://it.php.net/manual/en/language.namespaces.faq.php">FAQ from the official manual</a>, which contain much more code than my examples, or ask a question in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phparch.com/2010/03/namespaces-in-php/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Programming: you&#039;re doing it wrong</title>
		<link>http://www.phparch.com/2010/03/programming-youre-doing-it-wrong/</link>
		<comments>http://www.phparch.com/2010/03/programming-youre-doing-it-wrong/#comments</comments>
		<pubDate>Wed, 10 Mar 2010 20:29:33 +0000</pubDate>
		<dc:creator>Marco Tabini</dc:creator>
				<category><![CDATA[Opinion]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[technology]]></category>

		<guid isPermaLink="false">http://www.phparch.com/?p=4304</guid>
		<description><![CDATA[Software development is the land of egos and opinions—and it seems that, no matter how bad we try, we're always doing things the wrong way. But why?]]></description>
			<content:encoded><![CDATA[<p><a href="http://beta.phparch.com/wp-content/uploads/2010/03/3952587062_31a3593aa5.jpg"><img class="alignleft size-thumbnail wp-image-4305" title="3952587062_31a3593aa5" src="http://www.phparch.com/files/2010/03/3952587062_31a3593aa5-150x150.jpg" alt="" width="150" height="150" /></a>The year 2010 marks the twentieth anniversary of my professional involvement with the IT industry; in two decades, I have learned that programming, more than any other profession below “Keith Richards,” seems to attract people who have a certain ego. I don&#8217;t mean to say that we&#8217;re all megalomaniacs in search for a country to run, but there certainly is no lack of opinionated types in our industry.</p>
<p>The result is that a programmer who wants to make a name for herself soon finds out that it takes an extremely thick skin to survive in this world—even if you try your best to avoid being caustic, chances are that others around you won&#8217;t. In the world of computers, people have to volume settings: loud, and extra loud. To borrow lamely from pop culture, our amps all <em>start</em> at eleven.</p>
<p>The question is: <em>why?</em></p>
<h2>Critic&#8217;s Corner</h2>
<p>One of the things that I have learned in twenty years of attempting to program is that <em>we&#8217;re all doing it wrong</em>. You. Me. Everybody.</p>
<p>No matter how advanced the techniques that we use, there is always something that we could be doing better. Do you think that static methods are convenient? Sure, they work—but His Holiness Martin Fowler has decreed that Singletons are the correct way of handling static data. Except, of course, that he also told us that dependency injection is a much better way of handling external dependencies.</p>
<p>Which one is right?</p>
<p>The real problem is that the answer to that question is, “yes.” That&#8217;s because it lacks a specific <em>context</em> in which it can be inserted. Dependency injection may be the correct answers in some situations, while singletons may be perfect for your needs in others. Without in-depth knowledge of the circumstances in which a particular problem presents itself, there is no particular way to offer a definitive solution.</p>
<h2>Meanwhile, in the Bat Cave…</h2>
<p>While we stand and argue the finer points of computer science, we often lose sight of our primary mission: <em>enabling processes</em>. A programmer is first of all an artisan: proud of her work, but most productive when she is <em>making</em> something.</p>
<p>Somewhere along the lines, we&#8217;ve somehow managed to convince ourselves that we are <em>artists</em>. We have stopped debating differences on their merits within the context of enabling us to get things done—instead, we argue them endlessly in the abstract, as if writing code were both means and end. Like the CIO who sets a company&#8217;s IT strategy based on what&#8217;s on the back cover of the latest issue of <em>Information Week</em>, we&#8217;re moving from fad to fad without stopping to consider that technology is a <em>tool</em> and not a substitute for our own responsibility to make choices.</p>
<p>Meanwhile, those who somehow manage to remember that software <em>is</em> a tool achieve great success even if their code leaves a lot to be desired. When I open a PHP file inside the WordPress codebase, I feel like I just boarded a time machine that&#8217;s taken me back to the way we used to write PHP code six or seven years ago—and don&#8217;t even get me started on what I think of Drupal.</p>
<p>Yet, despite the fact that their code looks like it was written by someone who has no idea who Martin Fowler is and probably thinks that dependency injection is a medical technique for weaning addicts off of opiates, both those products undeniably work, and work well—not to mention the fact that they are very widely used.</p>
<p>More than that, they&#8217;re actively maintained, updated and upgraded—despite the fact that, according to what the artists tell us, software written using less-than-optimal techniques should be unmaintainable, buggy and unreliable.</p>
<p>If you&#8217;re agonizing over whether you&#8217;re writing good code, let me spare you the anguish: you&#8217;re doing it wrong—except if your code works, in which case you most definitely are doing it right.</p>
<p><em>Image credit: <a href="http://www.flickr.com/photos/adeepbreath/3952587062/">Adam Swank</a></em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.phparch.com/2010/03/programming-youre-doing-it-wrong/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
	</channel>
</rss>

