<?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>Terminus a Quo &#187; PHP</title>
	<atom:link href="http://abing.gotdns.com/posts/category/code-and-consequences/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://abing.gotdns.com</link>
	<description>Because you can never have too many blogs on the Internet...</description>
	<lastBuildDate>Tue, 19 May 2009 00:23:13 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Ditching PHP: Alternatives to PHP</title>
		<link>http://abing.gotdns.com/posts/2008/ditching-php-alternatives-to-php/</link>
		<comments>http://abing.gotdns.com/posts/2008/ditching-php-alternatives-to-php/#comments</comments>
		<pubDate>Wed, 26 Nov 2008 08:46:03 +0000</pubDate>
		<dc:creator>nimrod.abing</dc:creator>
				<category><![CDATA[Code and Consequences]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Perl]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://abing.gotdns.com/?p=222</guid>
		<description><![CDATA[You have worked around the quirks and you have lived with the inconsistencies. You have stood by and watched your code fail spectacularly between minor point releases. You scrambled to fix your code&#8217;s dependence on register_globals set to on when they got turned off by default in version 4.2.0. You have lived with the disappointment [...]
<p>a</p>
]]></description>
			<content:encoded><![CDATA[<p>You have worked around the quirks and you have lived with the inconsistencies. You have stood by and watched your code fail spectacularly between minor point releases. You scrambled to fix your code&#8217;s dependence on <code>register_globals set</code> to on when they got turned off by default in version 4.2.0. You have lived with the disappointment when version 5 failed to deliver on better object orientation. There have been a lot of warning signs telling you to look for better alternatives, but still you persevered. Then came the recent changes that really make you shake your head in disbelief. Face it, PHP&#8217;s direction as of late has really taken a downturn. You&#8217;re thinking it&#8217;s time to look for alternatives.</p>

<p>If you are one of those folks who have been using PHP <strong>and nothing but PHP</strong> for a long time you will be hard pressed to find an alternative. PHP is, after all, one of those things that are &#8220;easy to get into, but difficult to get out of&#8221;. PHP lures you in with its forgiving nature, vast library of pre-built extensions, ease of deployment and just plain &#8220;instant gratification&#8221;. It&#8217;s easy to forget that there are other languages for server-side programming/scripting.</p>

<p><span id="more-222"></span></p>

<h2>More Tools for your Toolbox</h2>

<p>When I was teaching CS classes back then, I always told my students <strong>never rely on a single programming language and never tie yourself to a single platform</strong>. I have always stressed the importance of learning more than one programming language and making sure that whatever you do, do it cross-platform if possible. By not limiting yourself to one language or platform, you will be able to develop solutions using the right tools for the problem at hand.</p>

<p>The following is a short list of programming languages that I have used in the past. These are my &#8220;bread and butter&#8221; languages in addition to PHP. These are also the reasons why I found it easy to ditch PHP. If you have never used any other programming language besides PHP, perhaps you should take a look at what else is out there.</p>

<h2>One Interface Behind Them All</h2>

<p>In theory, you can use <strong>any</strong> programming language to do server-side programming. You read that right: you can use any programming (or scripting) language. You can use C, C++, Fortran, Haskell, Java, Lisp, Lua, Perl, PHP, Python, Ruby, and so on. You can use whatever you want, as long you are able to receive input and send output via the Common Gateway Interface or CGI.</p>

<p>Server-side programming/scripting essentially involves two basic operations:</p>

<ol>
<li>Receiving and acting on a <strong>request</strong>;</li>
<li>Sending back a <strong>response</strong>.</li>
</ol>

<p>CGI acts as a bridge between your web server and your server-side program/script. When your web server receives a request and it sees that request as a request to execute a program/script on the server, it will set up everything that is necessary to run your program/script. It then runs the program/script, captures its output, if any, and sends it back to the client who issued the request. In Unix terms, any program/script that can take input from stdin and send output to stdout can be used on a web server that supports CGI. This is an overly simplified description. If you wish to learn more about CGI, use <a href="http://www.google.com/search?hl=en&#038;q=common+gateway+interface">&#8220;the Google&#8221;</a>.</p>

<p>Because the server runs the CGI program/script as an external process to handle each request, this means that there is an overhead for each request. To boost performance, modern web servers have come up with ways of eliminating or reducing the overhead from external process creation. For instance, Apache allows you to create modules that act as filters and handlers for requests. In most cases, PHP will have been installed as an Apache handler on your server which embeds the PHP interpreter in the running Apache process, eliminating the need to create an external process to run your PHP script. There is also an extension to the CGI standard called <a href="http://www.fastcgi.com/">FastCGI</a> which takes a different approach. FastCGI runs several instances of your program/script as long-running background processes. The webserver then connects to these processes whenever a requests requires the use of CGI, sends the request and collects the response and sends it back to the client.</p>

<p>Of course, these days you care less about the details and worry more about what your program/script does.</p>

<h2>Is it &#8220;Programming&#8221; or is it &#8220;Scripting?&#8221;</h2>

<p>At the heart of it, programming is programming and scripting is programming using a scripting language. In the early days, it&#8217;s easy to differentiate between &#8220;scripting&#8221; and &#8220;programming&#8221;. Scripts were written using &#8220;interpreted&#8221; programming languages which typically ran inside another program (e.g., CAD with Lisp scripting) or a stand-alone interpreter. &#8220;Programs&#8221;, in the original sense of the word, were written using &#8220;compiled&#8221; programming languages.</p>

<p>These days, the distinction has been blurred with the advent of <strong>compiled</strong> programming languages that are run using an interpreter. Java is just one example of this. You write your Java program and then compile it into machine-independent <strong>byte-code</strong> which you then run using a Java virtual machine or JVM. A JVM is essentially an interpreter but these days, we also have the so-called JVM with Just-in-Time compilation which maps machine-independent byte-code into native instructions for the CPU running the VM.</p>

<p>It&#8217;s all become so confusing these days with all the recent developments in VM technology. The distinction between &#8220;scripting&#8221; and &#8220;programming&#8221; has eroded. Personally I just prefer to call it <strong>programming</strong>. So from this point onwards, I will simply use the term &#8220;programming&#8221; to refer to &#8220;scripting&#8221; as well and &#8220;programs&#8221; to refer to &#8220;scripts&#8221;.</p>

<p>One more thing: Knowing how to write HTML and CSS does not make you a programmer, so please stop calling yourself a programmer or &#8220;coder&#8221; if all you know is HTML and CSS.</p>

<h2>The Duct Tape of the Internet</h2>

<p>Let&#8217;s begin with the grand daddy of server-side programming: <a href="http://www.perl.org/">Perl</a>. Created by Larry Wall in 1987, it has evolved into a true, general-purpose programming language. It was developed primarily to automate system administration on Unix systems. It began to gain popularity in the early 1990&#8217;s as a convenient way to write CGI scripts. PHP can trace it&#8217;s origins back to a CGI script written by Rasmus Lerdorf using Perl. That&#8217;s right, a scripting language begat <em>another</em> scripting language. You can see shades of Perl in PHP, the most visible is the use of the $ symbol to start a variable name.</p>

<p>Perl may come across as a quirky, cryptic language to some. It has also been the butt of jokes in recent times with the advent of newer (and sexier) programming languages. The Perl mantra TIMTOWTDI (there is more than one way to do it) is both a blessing and a curse. Take printing a progress bar for example. As one person found out by asking the Perl monks, <a href="http://www.perlmonks.org/?node_id=396839">TMTOWTDI</a>. But make no mistake. Perl is a very powerful language, with a friendly community and a <a href="http://cpan.org/">huge library of pre-written modules</a>.</p>

<p>The standard Perl installation comes with the CGI module which allows you to get up and running with CGI very quickly. You can use Perl to write a simple CGI script without using the CGI module. However, using the CGI module frees you from having to deal with a raw CGI environment. It also gives you with useful functions for handling query strings and forms, URL escaping, and error handling.</p>

<p>It also comes with a standard for database interfaces and drivers (DBI and DBD). DBI will usually come pre-installed along with commonly used database drivers. If you are familiar with ODBC or if you have played around with PDO, the Perl DBI is similar in spirit. It provides you with a consistent interface for database access and more importantly, it gives you <strong>prepared statements</strong> even if the underlying database does not support it.</p>

<p>More importantly, most virtual hosting shops support already support Perl in addition to PHP. You will probably have two options, depending on your hosting provider. First option would be to write your programs as just plain CGI programs and upload them to a special directory on your account. Second option would be to write your program to take advantage of <a href="http://perl.apache.org/">mod_perl</a> if it is installed by your hosting provider. mod_perl not only allows you to write CGI programs, it also allows you to create Apache modules using Perl.</p>

<h2>Over-Engineered Beyond Help</h2>

<p>Next up we have the programming language that no self-respecting software &#8220;engineer&#8221; can do without: Java. Although it has all the required facilities needed to write CGI programs, if you must do something in Java, you should do it properly. And the proper way of server-side programming in Java is to write a Java Servlet. In order to do that, you need to run it inside a Servlet Container such as <a href="http://tomcat.apache.org/">Apache Tomcat</a>.</p>

<p>Java already has database connectivity covered with its standard JDBC. Odds are that your servlet container can also run JSP&#8217;s which allow you to embed Java code in your markup. Your servlet container then takes these JSP&#8217;s, compiles them into a servlet when handling the first request and uses the compiled servlet to handle subsequent requests.</p>

<p>As you have probably learned by now (or not), it is better to separate your program into distinct areas using the Model-View-Controller paradigm. Java supports this out of the box. You have POJO&#8217;s (plain old Java objects) to use for your model. The servlet serves as controller. JSP provides you with the view. Once you have the basics nailed down, it&#8217;s all very simple onwards. Or not&#8230;</p>

<p>As your program grows in size and complexity you will find the simple MVC approach using POJOs, servlets and JSP&#8217;s become unwieldy at best. You will be looking for a better solution. Java has a standard for developing large scale web applications too. J2EE is a collection of standards that encompass everything you need to develop large scale web applications and service oriented applications (SOA&#8217;s). Newbies will probably be overwhelmed by the amount of complexity involved in developing and deploying large-scale apps using J2EE. It has more acronyms than a bowl of alphabet soup. Once you&#8217;ve finished wading through your acronym soup, prepare to swim in XML tag soup. Almost everything in a J2EE server is configured using XML. But then again, developing and deploying a large-scale J2EE app was never meant to be a job for a lone developer and there are tools you can use to tame all that XML.</p>

<p>As for hosting your Java apps, typically you need to find a specialized hosting service of which there is no short supply.</p>

<h2>Ooooooh! Shiny!</h2>

<p>Then there&#8217;s <a href="http://www.ruby-lang.org/en/">Ruby</a>. First released to the public in 1995 by Yukihiro Matsumoto, it was an obscure programming language from Japan that exploded in popularity in recent years (due to a well-marketed web programming framework). As one fellow so succinctly put: &#8220;Ruby is the language for trendy, non-conformists.&#8221;</p>

<p>Ruby by itself is a very capable language with a large set of libraries included as standard. The CGI library is one of them so you can also get to writing server-side programs in no time. Like Perl and Java, it also comes with a standard library for interfacing with databases.</p>

<p>I tried Ruby some time early last year but I find its reliance on on <code>begin</code> and <code>end</code> to be a major annoyance at best. That&#8217;s the reason why I hated programming in Pascal and VB so much. Come on, if braces worked for C, C++, Java, Javascript, Perl, PHP, etc. why bother using whole words to delineate blocks of code? Another sticking point, at least at the time, was performance. For small one-off scripts, it&#8217;s pretty decent. However, for larger more complex programs which are spread across several files, performance really sucks! The time it takes to launch the interpreter, byte compile your code and run it was simply unacceptable for me. If you&#8217;re going to use Ruby for CGI programming, use FastCGI or some other way of keeping a cached copy of your byte-compiled code in memory.</p>

<p>With those two aside, I find some features that make Ruby hard to resist. There&#8217;s &#8220;monkey patching&#8221;. Ruby classes are open classes. This means two things: you can spread class definitions across multiple files and you can modify built-in or standard library class behavior. Being able to spread class definitions across files helps to make your code more manageable as it grows in complexity and size. By modifying behavior of built-in or standard library classes you&#8217;re able to create semantics that are more suited to the job at hand. This can also be a problem, especially if your program is reliant on third-party libraries, as it is possible that the modified behavior is not what you really want. But when done carefully, it can extend the usefulness of existing classes (like to what <a href="http://mootools.net/">Mootools</a> does for Javascript).</p>

<p>Ruby also makes it relatively simple to map data from a text file or database record into a dynamically generated class at run-time. This proves useful in creating ORM&#8217;s (object-relational mappings). Most Java ORM&#8217;s use a clunky approach glued together with unholy amounts of XML. Ruby makes it easy by providing the facilities necessary as built-ins.</p>

<p>Another great feature is class composition. This is similar to the concept of interfaces and mixins in other languages. You define a set of methods and properties in a <code>module</code>. When you need them in your class, you simply <code>include</code> the module.</p>

<p>As for finding hosting providers that support Ruby, thanks to a popular web programming framework, most hosting providers now support Ruby in addition to PHP and Perl. Just like Java however, you can get better bang for your buck by going with a specialized Ruby hosting package.</p>

<h2>Batteries Included</h2>

<p>Now we come to my programming language of choice: <a href="http://www.python.org/">Python</a>. While using whitespace to delimit blocks of code may seem strange to those who come from the &#8220;bracketed&#8221; programming languages such as C, Java, Perl or PHP, it actually makes your programs easy to read <strong>by default</strong>. You don&#8217;t need to remember any silly coding and indenting conventions. As long as you use a consistent means of indenting your code (4 spaces is recommended), you are pretty much set when it comes to readability. It was a bit uncomfortable at first but blocks delineated by indentation sort of grows on you eventually.</p>

<p>With that <strong>single</strong> &#8220;unusual&#8221; quirk aside, Python has all of the tools you need to get started with server-side programming: &#8220;Batteries Included&#8221;. Simply <code>import</code> the cgi module in your code and start plugging away at your program. However just like in Java, there is a standard way of doing things and the standard way of server-side programming using Python is through the use of <a href="http://www.python.org/dev/peps/pep-0333/">WSGI</a>. Python&#8217;s WSGI is similar in spirit to Java&#8217;s Servlet specification. It defines a standard way of writing programs that have to interface with a web server using a request-response model. It takes the server&#8217;s execution environment, the client&#8217;s request, and the server&#8217;s response and packages it into one coherent specification.</p>

<p>One more thing that I like about programming in Python is that your program sort of describes itself. You spend less time writing descriptive comments as to what a section of your code does, unlike other programming languages. Chances are that you can write a Python program now without any documenting comments, come back six months later and look at your code and you will still be able to read and understand what it does.</p>

<p>Performance-wise, Python has consistently outperformed PHP and Ruby as of late. Python programs are compiled into byte-code before it gets executed by the Python VM (interpreter) just like Java. However, unlike Java, there is no explicit compilation step necessary. Unlike Java, Python can run your code regardless of whether or not it is in the byte-code compiled form. Your byte-compiled Python code essentially acts as an on-disk cache for the VM. When you first run your program, the Python interpreter will byte-compile your code and if it can, it will write the byte-compiled code into a file with a .pyc extension. The next time you run your program, the interpreter will check if there is a .pyc file present. If found, it will check to see if your source file is newer than the .pyc file. If your .pyc file is up to date, the interpreter skips the byte-compilation step and runs the .pyc file instead. If your source file is newer, it will byte-compile it and try to write it to disk. This is another reason why I prefer Python over anything else. I can distribute just the .pyc files without the .py source files. I am all for &#8220;open source&#8221; but there times when you just don&#8217;t want clients to be dicking around with your code.</p>

<p>As for libraries, chances are good that the standard Python installation already has everything you need. Python also comes with a standard for database interfaces called DBI, which like its Perl counterpart, provides you with a consistent interface regardless of what database you are using. It also provides you with prepared statements which can be emulated in the driver in case your database does not support it.</p>

<p>Just like Ruby and Java, you are better off going with a specialized Python hosting package if you are going to do WSGI. If you only need to write CGI programs in Python, then many hosting providers already support Python in addition to Perl, PHP, and Ruby.</p>

<p>So there you have it. I hope this goes to show that PHP is not the be all and end all to programming.</p>

<p>a</p>
]]></content:encoded>
			<wfw:commentRss>http://abing.gotdns.com/posts/2008/ditching-php-alternatives-to-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Definitely Time To Ditch PHP</title>
		<link>http://abing.gotdns.com/posts/2008/definitely-time-to-ditch-php/</link>
		<comments>http://abing.gotdns.com/posts/2008/definitely-time-to-ditch-php/#comments</comments>
		<pubDate>Mon, 27 Oct 2008 03:29:54 +0000</pubDate>
		<dc:creator>nimrod.abing</dc:creator>
				<category><![CDATA[Code and Consequences]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[You are doing it WRONG!!!]]></category>

		<guid isPermaLink="false">http://abing.gotdns.com/?p=211</guid>
		<description><![CDATA[Good bye PHP. You have been a good bread and butter language for me. Sorry to say the dumbosity of the design decisions being made about you are too much to live with. It&#8217;s time I moved on to bigger and better things with a better sense of direction.

Reading the IRC chat log that lead [...]
<p>a</p>
]]></description>
			<content:encoded><![CDATA[<p>Good bye PHP. You have been a good bread and butter language for me. Sorry to say the <a href="http://wiki.php.net/_media/rfc/php.ns.txt?id=rfc%3Anamespaceseparator&#038;cache=cache">dumbosity</a> of the design decisions being made about you are too much to live with. It&#8217;s time I moved on to <a href="http://python.org/">bigger</a> and <a href="http://djangoproject.com/">better</a> things with a <a href="http://www.python.org/dev/peps/">better sense of direction</a>.</p>

<p><span id="more-211"></span></p>

<p>Reading <a href="http://wiki.php.net/_media/rfc/php.ns.txt?id=rfc%3Anamespaceseparator&amp;cache=cache">the IRC chat log that lead to the &#8220;backslash as namespace separator&#8221; decision</a> just affirms my impression that the PHP language is in the hands of neurotic, crack-smoking monkeys. Well except for a few people like Dmitry. Apparently there are two problems with &#8220;::&#8221; that prove too difficult for them to solve:</p>

<ol>
<li><p>There are some modifications needed for &#8220;::&#8221; to work properly but these modifications will break existing code. I would say, what the hell! Break existing code! PHP6 will break existing code anyway. But no, they also want namespaces in PHP5 so there!</p></li>
<li><p>The engine can&#8217;t detect ambiguity without calling autoload. It introduces the so-called &#8220;autoload bomb&#8221;. Apparently, calling autoload once for each namespace as Dmitry suggested is &#8220;impracticable[sic] because it relies on the programmer to know when ambiguity arises&#8221;. Huh?!? Forgive me but isn&#8217;t it the job of the compiler/interpreter to detect such an ambiguity and <strong>tell the programmer</strong>???</p></li>
</ol>

<p>So instead of fixing the fundamental problems with the engine, they want to use the band-aid solution of adding a different syntax for namespaces. Oh wait, maybe it&#8217;s because the engine is so horribly designed that it&#8217;s impossible to write in sensible changes without having the whole thing fall apart completely?</p>

<p>I have been fighting so hard to keep <a href="http://tnx.nl/php.html">this</a> from swaying me away from PHP. I have lived through and worked around the inconsistencies and quirks of the language, but this &#8220;backslash as namespace separator&#8221; crap is the last straw. It sucks that I have to maintain a lot of PHP code but from this point onwards, I will no longer use PHP for new projects.</p>

<p>a</p>
]]></content:encoded>
			<wfw:commentRss>http://abing.gotdns.com/posts/2008/definitely-time-to-ditch-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Is It Time to Ditch PHP?</title>
		<link>http://abing.gotdns.com/posts/2008/is-it-time-to-ditch-php/</link>
		<comments>http://abing.gotdns.com/posts/2008/is-it-time-to-ditch-php/#comments</comments>
		<pubDate>Sun, 26 Oct 2008 08:18:06 +0000</pubDate>
		<dc:creator>nimrod.abing</dc:creator>
				<category><![CDATA[Code and Consequences]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[You are doing it WRONG!!!]]></category>

		<guid isPermaLink="false">http://abing.gotdns.com/?p=204</guid>
		<description><![CDATA[PHP has long been a bread and butter language for me when it came to web-based projects. It&#8217;s what got me started in the whole web development business and essentially kick-started my whole career as a systems developer. But alas, recent developments in PHP land come as an unwelcome surprise. I&#8217;m talking about the much [...]
<p>a</p>
]]></description>
			<content:encoded><![CDATA[<p>PHP has long been a bread and butter language for me when it came to web-based projects. It&#8217;s what got me started in the whole web development business and essentially kick-started my whole career as a systems developer. But alas, recent developments in PHP land come as an unwelcome surprise. I&#8217;m talking about the much anticipated (for me anyway) namespace support. I have documented my basic gripes about PHP <a href="http://abing.gotdns.com/posts/2007/new-php5-based-framework-project-php5-and-lack-of-namespace-support-among-other-things/">elsewhere</a>. So I won&#8217;t go rambling about them again. I was excited to hear about namespaces <strong>finally</strong> getting implemented in PHP6 and backported to PHP5. But then when you read about <a href="http://wiki.php.net/rfc/namespaceseparator">bullshit like this</a> you can&#8217;t help but wonder if the language&#8217;s direction has been taken over by a pack of neurotic, crack-smoking monkeys. Namespaces are a very important feature if one were to write large amounts of code without having to worry about symbol name clashes.</p>

<p><span id="more-204"></span></p>

<p>So, they want to replace the de facto standard namespace separator &#8220;::&#8221; with &#8220;\&#8221;. That&#8217;s right: replace double-colon with a backslash! Why? It&#8217;s because &#8220;::&#8221; is already being used in class method invocations and it will cause problems during parsing. Consider the following:</p>

<pre>class Lol {
    public static function whut() {
    }

namespace Lol;

function whut() {
}
</pre>

<p>Elsewhere:</p>

<pre>Lol::whut();
</pre>

<p>When you write <code>Lol::whut()</code>, which one are you talking about? Is it the <code>static</code> function in the class <code>Lol</code>? Or is it the function in the <code>Lol</code> namespace? I can think of a few solutions to this very simple problem besides changing the damned separator character.</p>

<ol>
<li><p>Throw an exception during parsing/compilation and complain that the symbol Lol has already been defined. Ideally it should say something sensible like: &#8220;Class name &#8216;Lol&#8217; defined in main namespace conflicts with existing namespace definition &#8216;Lol&#8217; found in <strong>FILE</strong>, line <strong>LINE</strong>.&#8221; For dynamically generated code, throw a runtime error and halt program execution. This is how C++ handles it, I can&#8217;t see why PHP can&#8217;t do the same. I would prefer it this way because I don&#8217;t want some moron programmer who is using my Lol library to write a class named Lol in the main namespace!</p></li>
<li><p>Throw an exception like in #1 but make it a non-fatal exception and just let the class method defined in the main namespace take precedence. Or even let the function in the namespace take precendence. Do it one way over the other <em>but tell the programmer that there is a problem</em> with <strong>his code</strong>!</p></li>
<li><p>Force <code>Lol::whut()</code> to resolve to the class method and <code>::Lol::whut()</code> to resolve to the function defined in namespace <code>Lol</code>. Or vice versa.</p></li>
</ol>

<p>I would really love to see arguments leveled against the 3 solutions above because changing the separator character is just plain stupid. Oh, and it&#8217;s butt ugly too. <strike>Sure it&#8217;s just in RFC but if this sort of stupid shit makes it into PHP6 then it&#8217;s time to say bye-bye PHP&#8230;</strike> It looks like they have their hearts set on using backslash as the namespace separator and <a href="http://news.php.net/php.internals/41374">it&#8217;s pretty much set in stone</a>.</p>

<p>On a side note, when I was reading the RFC I had to take a second look at the date to make sure that it does not say April 1, 2008. They were considering the &#8220;smiley&#8221; as a namespace separator?!? Surely you jest!</p>

<p>a</p>
]]></content:encoded>
			<wfw:commentRss>http://abing.gotdns.com/posts/2008/is-it-time-to-ditch-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>When is a Closure not a Closure?</title>
		<link>http://abing.gotdns.com/posts/2008/when-is-a-closure-not-a-closure/</link>
		<comments>http://abing.gotdns.com/posts/2008/when-is-a-closure-not-a-closure/#comments</comments>
		<pubDate>Tue, 22 Jul 2008 04:08:22 +0000</pubDate>
		<dc:creator>nimrod.abing</dc:creator>
				<category><![CDATA[Code and Consequences]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[You are doing it WRONG!!!]]></category>

		<guid isPermaLink="false">http://abing.gotdns.com/?p=173</guid>
		<description><![CDATA[Answer: When it&#8217;s a PHP closure. It appears that PHP will have closures in 5.3. But as per usual, it does not work in ways that you would expect it to work. See the comment by &#8220;sapphirecat&#8221; on this
<p>a</p>
]]></description>
			<content:encoded><![CDATA[<p>Answer: When it&#8217;s a <a href="http://wiki.php.net/rfc/closures">PHP closure</a>. It appears that PHP will have closures in 5.3. But as per usual, it does not work in ways that you would expect it to work. See the comment by &#8220;sapphirecat&#8221; on this <a href="http://www.toosweettobesour.com/2008/07/21/php-53-and-closures/trackback/"article</a>. There still appears to be a problem when you &#8220;rope&#8221; off a global:</p>

<blockquote>
  <p>So they seem to have taken the usual half-broken approach: you can have read-only closures which are immune to changes to a global variable, or you can have read-write closures which remember changes, but those changes leak back into the global variable.</p>
</blockquote>

<p>Oops! Closures are not supposed to do that! It sort of defeats the purpose of having closures in the first place. There is a workaround to the problem but that is one more quirk that you have to remember when working with PHP. Two steps forward, one step back.</p>

<p>a</p>

<p></a></p>
]]></content:encoded>
			<wfw:commentRss>http://abing.gotdns.com/posts/2008/when-is-a-closure-not-a-closure/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>New PHP5-based Framework Project, PHP5 and Lack of Namespace Support, Among Other Things&#8230;</title>
		<link>http://abing.gotdns.com/posts/2007/new-php5-based-framework-project-php5-and-lack-of-namespace-support-among-other-things/</link>
		<comments>http://abing.gotdns.com/posts/2007/new-php5-based-framework-project-php5-and-lack-of-namespace-support-among-other-things/#comments</comments>
		<pubDate>Mon, 13 Aug 2007 08:21:56 +0000</pubDate>
		<dc:creator>nimrod.abing</dc:creator>
				<category><![CDATA[Code and Consequences]]></category>
		<category><![CDATA[Django]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://abing.gotdns.com/posts/2007/new-php5-based-framework-project-php5-and-lack-of-namespace-support-among-other-things/</guid>
		<description><![CDATA[I have been spending way too much time programming with Python and Django. I was looking for something like Django but written for PHP5. I needed a way to go forward with my PHP-based projects since PHP4 will no longer receive updates next year.

Not satisfied with the PHP5 frameworks I found I decided to write [...]
<p>a</p>
]]></description>
			<content:encoded><![CDATA[<p>I have been spending way too much time programming with Python and Django. I was looking for something like Django but written for PHP5. I needed a way to go forward with my PHP-based projects since PHP4 will no longer receive updates next year.</p>

<p><span id="more-102"></span></p>

<p>Not satisfied with the PHP5 frameworks I found I decided to write my own (again). I looked at one particular candidate &#8212; [Picora &trade;: PHP Micro Framework][picora]. It&#8217;s small and focused on doing one thing: provide an MVC framework for PHP. While it has both qualities that I was looking for in an MVC framework there are a couple of issues that I found:</p>

<ul>
<li>it currently lacks an ActiveRecord implementation.</li>
</ul>

<blockquote>Note that the model() calls use a PHP ActiveRecord implementation which is not part of Picora, substitute with your own database logic for the time being.</blockquote>

<ul>
<li>it makes the same (IMHO) mistake as CakePHP and Rails in that actions are mapped directly into methods in your Controller class without giving you the option of delegating it to a separate class. While there&#8217;s nothing wrong with this, I found that having all your actions in one big file becomes unwieldy when your project grows. Which was why I came up with [a modified action mapper for CakePHP][cakephp-sucks01].</li>
</ul>

<p>So, for now Picora &trade; doesn&#8217;t quite cut it for me yet. I began writing a new framework, based on some ideas I had from a year ago as well as taking a lot of inspiration from Django. I am writing the model class hierarchy based on Django&#8217;s excellent ORM. This will also be my first large project written using PHP5. Needless to say it has been pretty frustrating to find that PHP5 lacks namespace support. I was left wondering, &#8220;With PHP5, they practically went out and copied Java and yet they forgot to implement namespaces?!?&#8221;.</p>

<p>I did a search on Google for &#8220;php namespace support&#8221; and what I got was a depressing state of affairs for this important feature. It turns out that at the time, PHP5 namespace support is not a simple thing to implement and one of the major issues is the namespace separator. Maybe this is a testament to the fact that the PHP language is horribly broken an a multitude of places? Or maybe it&#8217;s because &#8220;design by committee&#8221; does not work? I found [one particularly entertaining post about the issue][shalosh] from 2005 and [a more recent posting][phpnamespaces] citing a [patch that implements namespaces for PHP6][phpnamespace-patch]. It looks like [namespace support will be in <strong>PHP6</strong>][zend-weekly]. I can only hope that this will be backported into a point release for PHP5.</p>

<p>Among other things I would like to see in PHP6:</p>

<ul>
<li>Closures or <strong>real</strong> anonymous functions at the very least. No, <code>create_function()</code> does not count!</li>
<li>Inner classes.</li>
<li>Inner functions.</li>
<li>Make built-ins like <code>include()</code>, <code>include_once()</code>, <code>require()</code>, and <code>require_once()</code> throw exceptions in addition to their original behavior. But it would really help to do away with the old <code>*_error_handler()</code> way of doing things.</li>
</ul>

<p>These are just some of the features that I <em>wish</em> was in PHP, ever since PHP4.</p>

<p>[picora]: http://livepipe.net/projects/picora/ &#8220;Picora &trade;: PHP Micro Framework&#8221;
[cakephp-sucks01]: http://abing.gotdns.com/posts/2006/cakephp-delegating-actions-to-separate-classes/ &#8220;CakePHP: Delegating Actions to Separate Classes&#8221;
[shalosh]: http://blog.phpdoc.info/archives/27-+1-for-Shalosh-Nekudotayim.html &#8220;Shalosh Nekudotayim&#8221;
[phpnamespaces]: http://www.gravitonic.com/blog/archives/000418.html &#8220;PHP Namespace Support&#8221;
[phpnamespace-patch]: http://news.php.net/php.zend-engine.cvs/5894 &#8220;PHP6 Namespace Support Patch&#8221;
[zend-weekly]: http://devzone.zend.com/article/2336-Zend-Weekly-Summaries-Issue-348 &#8220;Zend Weekly Summaries&#8221;</p>

<p>a</p>
]]></content:encoded>
			<wfw:commentRss>http://abing.gotdns.com/posts/2007/new-php5-based-framework-project-php5-and-lack-of-namespace-support-among-other-things/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>I Am No Longer Tracking CakePHP</title>
		<link>http://abing.gotdns.com/posts/2007/i-am-no-longer-tracking-cakephp-and-new-projects/</link>
		<comments>http://abing.gotdns.com/posts/2007/i-am-no-longer-tracking-cakephp-and-new-projects/#comments</comments>
		<pubDate>Wed, 11 Jul 2007 07:25:09 +0000</pubDate>
		<dc:creator>nimrod.abing</dc:creator>
				<category><![CDATA[CakePHP]]></category>
		<category><![CDATA[Code and Consequences]]></category>
		<category><![CDATA[Django]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Yes, I do have a Life.]]></category>

		<guid isPermaLink="false">http://abing.gotdns.com/posts/2007/i-am-no-longer-tracking-cakephp-and-new-projects/</guid>
		<description><![CDATA[Title says it all. I am no longer tracking the CakePHP project and therefore my CakePHP modifications project is now officially dead. This is mostly due to time constraints but there are other reasons as well. I will not go into the details for the other reasons but those who know me already know what [...]
<p>a</p>
]]></description>
			<content:encoded><![CDATA[<p>Title says it all. I am no longer tracking the CakePHP project and therefore my CakePHP modifications project is now <strong>officially dead</strong>. This is mostly due to time constraints but there are other reasons as well. I will not go into the details for the other reasons but those who know me already know what those reasons are.</p>

<p>Of course, hosting for these patches continues as well as my ThemeableView class which some CakePHP users out there found useful. If anyone else is interested in taking the reins for this class, please feel free to do so. No need to contact me or anything, but a trackback to this post would be nice so that I will know who is currently maintaining this class. This will allow me to direct them to you for any updates that you may post.</p>

<p>On another note, the project that has been taking much of my time lately is a new website for posting <a href="http://www.preownedcar.com/" title="Free online classified ads for cars, trucks, and bikes">free online classified ads for cars, trucks, and bikes</a>. This website is currently US-centric. We have plans to extend worldwide if all goes well with the current setup. So, if you&#8217;re in the US and you wish to sell your vehicle, or if you&#8217;re looking to buy a preowned car, truck, or bike check out <a href="" title="Free online classified ads for cars, trucks, and bikes">PreOwnedCar.com</a>. If you know someone with the same needs, please tell them about this site.</p>

<p>We are also currently in the final design phases for PhilWeavers Version 4. I am currently divided between doing this new version using Django as a base or simply going back to the drawing board and creating a new PHP5-based framework. We&#8217;ll see how this pans out in the later stages of development.</p>

<p>a</p>
]]></content:encoded>
			<wfw:commentRss>http://abing.gotdns.com/posts/2007/i-am-no-longer-tracking-cakephp-and-new-projects/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Two Months Working With Django&#8230; Wishing CakePHP had a Better ORM</title>
		<link>http://abing.gotdns.com/posts/2007/two-months-working-with-django-wishing-cakephp-had-a-better-orm/</link>
		<comments>http://abing.gotdns.com/posts/2007/two-months-working-with-django-wishing-cakephp-had-a-better-orm/#comments</comments>
		<pubDate>Thu, 08 Mar 2007 04:03:13 +0000</pubDate>
		<dc:creator>nimrod.abing</dc:creator>
				<category><![CDATA[CakePHP]]></category>
		<category><![CDATA[Code and Consequences]]></category>
		<category><![CDATA[Django]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://abing.gotdns.com/posts/2007/two-months-working-with-django-wishing-cakephp-had-a-better-orm/</guid>
		<description><![CDATA[I have been working with the Django Web framework for close to two months now and I&#8217;m loving it. Not so much for the free admin interface, but for the sheer ease of development that it provides. For the first time, I cared more about how my models are designed and not how they are [...]
<p>a</p>
]]></description>
			<content:encoded><![CDATA[<p>I have been working with the <a href="http://www.djangoproject.com/" title="Django Web framework">Django Web framework</a> for close to two months now and I&#8217;m loving it. Not so much for the <a href="http://www.djangoproject.com/documentation/overview/#a-dynamic-admin-interface-it-s-not-just-scaffolding-it-s-the-whole-house" title="A dynamic admin interface: It's not just scaffolding -- it's the whole house">free admin interface</a>, but for the sheer ease of development that it provides. For the first time, I cared more about how my models are designed and not how they are laid out and implemented in the database. For the two projects that I am working on, I have yet to write a custom SQL statement under Django.</p>

<p>It makes me wish CakePHP offered more when it comes to object-relational mapping. How I wish it was as simple as defining your models and running <code>php cake/scripts/bake.php syncdb</code>. CakePHP does it the other way around: you create the database first and then use <code>cake/scripts/bake.php</code> to create your models and views.</p>

<p><span id="more-81"></span></p>

<p>I found that Django&#8217;s way of doing ORM is significantly faster. You specify your models as Python classes using Django&#8217;s modeling API. You run <code>python manage.py syncdb</code> and Django takes care of generating the correct SQL for your database backend. It takes model relationships into account and also generates the correct foreign key constraints. Beautiful!</p>

<p>A similar system should also be possible to implement in CakePHP. I&#8217;ve been having a few ideas of how to go about it and hopefully, I can find the time to do them as an add-on to CakePHP 1.2.x (and hopefully, someone else is already working on the same thing).</p>

<p>Here is what I imagine it would look like:</p>

<pre><code>class User extends MetaModel {
    var $username;
    var $password;
    var $lastname;
    var $firstname;
    var $is_active;
    var $is_staff;
    var $is_admin;
    var $created;
    var $updated;

    function __construct() {
        $this-&gt;username = FieldFactory::CharField(&amp;#8217;Username&amp;#8217;, 32, IS_PK, IS_REQUIRED, NOT_NULL);
        $this-&gt;password = FieldFactory::CharField(&amp;#8217;Password&amp;#8217;, 64, NO_INDEX, IS_REQUIRED, NOT_NULL);
        $this-&gt;lastname = FieldFactory::CharField(&amp;#8217;Last Name&amp;#8217;, 64, INDEX, IS_OPTIONAL, NOT_NULL);
        $this-&gt;firstname = FieldFactory::CharField(&amp;#8217;First Name&amp;#8217;, 64, INDEX, IS_OPTIONAL, NOT_NULL);
        $this-&gt;is_active = FieldFactory::BooleanField(&amp;#8217;Active&amp;#8217;, IS_REQUIRED, NOT_NULL, false);
        $this-&gt;is_staff = FieldFactory::BooleanField(&amp;#8217;Staff&amp;#8217;, IS_REQUIRED, NOT_NULL, false);
        $this-&gt;is_admin = FieldFactory::BooleanField(&amp;#8217;Admin&amp;#8217;, IS_REQUIRED, NOT_NULL, false);
        $this-&gt;created = FieldFactory::DateTimeField(&amp;#8217;Created&amp;#8217;, NO_INDEX, IS_REQUIRED, NOT_NULL);
        $this-&gt;updated = FieldFactory::DateTimeField(&amp;#8217;Updated&amp;#8217;, NO_INDEX, IS_REQUIRED, NOT_NULL);
    }
}
</code></pre>

<p><code>FieldFactory</code> would have static methods for instantiating the correct field objects for each type. It would also have methods for generating constraints for implementing many-to-one and many-to-many relationships. I think a new model class is required to be able to do the additional magic without changing the current API.</p>

<p>I haven&#8217;t thought about how to implement the analogs of Admin and Meta inner-classes yet. I think those can be done as fields in the model, maybe <code>$this->__meta</code> and <code>$this->__admin</code>. As for QuerySets, Q objects and other classes in the Django DB API those are pretty much doable under PHP.</p>

<p>For SQL generation using the models, I imagine the backend will first load all the model classes found. Then models extending the MetaModel base class are instantiated and introspected to generate the correct DDL statements in database-specific SQL.</p>

<p>This is not a trivial undertaking and will take a lot of planning and thought. Model introspection and ORM should use as much of the existing CakePHP API as possible.</p>

<p>One last thing, if you are working on a similar system for CakePHP leave comments below. Remember: DRY.</p>

<p>a</p>
]]></content:encoded>
			<wfw:commentRss>http://abing.gotdns.com/posts/2007/two-months-working-with-django-wishing-cakephp-had-a-better-orm/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CakePHP Modifications is on Temporary Hiatus</title>
		<link>http://abing.gotdns.com/posts/2007/cakephp-modifications-is-on-temporary-hiatus/</link>
		<comments>http://abing.gotdns.com/posts/2007/cakephp-modifications-is-on-temporary-hiatus/#comments</comments>
		<pubDate>Wed, 03 Jan 2007 02:15:36 +0000</pubDate>
		<dc:creator>nimrod.abing</dc:creator>
				<category><![CDATA[CakePHP]]></category>
		<category><![CDATA[Code and Consequences]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://abing.gotdns.com/posts/2007/cakephp-modifications-is-on-temporary-hiatus/</guid>
		<description><![CDATA[I&#8217;m going to take a break from my CakePHP modifications project. I am currently working on a project using the Python-powered framework, [Django][django]. Needless to say, just like CakePHP it&#8217;s been improving with each and every iteration. Though it&#8217;s not even in &#8220;1.0&#8243; yet, the features it currently sports are very impressive and, dare I [...]
<p>a</p>
]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m going to take a break from my CakePHP modifications project. I am currently working on a project using the Python-powered framework, [Django][django]. Needless to say, just like CakePHP it&#8217;s been improving with each and every iteration. Though it&#8217;s not even in &#8220;1.0&#8243; yet, the features it currently sports are very impressive and, dare I say, inspiring! However, PHP has been my bread and butter for close to 3 years now. Though I have so many gripes with PHP as a language, I still find it useful and it still gets the job done.</p>

<p>CakePHP modifications will continue once I finish my current project and once CakePHP 1.2.x.x gets sorted out.</p>

<p><span id="more-76"></span></p>

<p>It&#8217;s interesting to see the direction that CakePHP 1.2.x.x is currently taking. It seems that most of the functionality I&#8217;m am currently working on with my modifications for 1.1.x.x is in the works for 1.2.x.x. Here&#8217;s the short list of features that I really need:</p>

<ul>
<li><p>Lazy-loaded models (already backported into 1.1.x.x) &#8212; This was one of the major gripes that I had with CakePHP as it loads class files for models that you do not even use. This feature increases performance and reduces memory footprint for very large applications with a large number of models.</p></li>
<li><p>Validator classes &#8212; This new feature allows for more complex data validation while maintaining the DRY principle. I never liked the idea of using simple regex strings for data validators. What if I wanted to do more complex data validation? (e.g. query a user database if a username already exists) In my old framework, I used validator classes when handling form data. Each form field has its own validator chain and can include as many validator objects as it needs.</p></li>
<li><p>i18n and l10n &#8212; Because it&#8217;s a big world out there and not everyone speaks English. There is now the beginnings of an internationalization and localization API in the framework.</p></li>
<li><p>User Authentication &#8212; Although it&#8217;s not clear yet where this is going, I expect that there would be an extensible authentication framework with support for both simple authentication (username+password) and challenge-response authentication (username+password+challenge token).</p></li>
</ul>

<p>Now, if only they could throw in a &#8220;standard&#8221; regression and unit testing framework and add a generous smattering of metaprogramming constructs into the mix&#8230;</p>

<p>I have also been following a very interesting discussion with regards to [using the built-in system ACL in limiting user access to data][acl]. The current ACL system built into CakePHP uses what&#8217;s called MPTT or Modified Pre-ordered Tree Traversal to navigate through a network of ACO&#8217;s and ARO&#8217;s. I have made my own MPTT implementation for the object system in my new CMS.The code for this is not for the faint of heart. Yet, the flexibility that you end up with is well worth the effort.</p>

<p>The current discussion on the list about ACL&#8217;s made me look deeper into my MPTT implementation. From what I can gather, it will not scale very well as the number of objects increase as it uses a recursive algorithm when reordering the tree traversal data. So now I&#8217;m off to look for a better implementation&#8230;</p>

<p>[django]: http://www.djangoproject.com/ &#8220;Django Project Home&#8221;
[acl]: http://groups-beta.google.com/group/cake-php/browse_thread/thread/263d3ffd6fb7533d &#8220;Using ACL to limit access to data&#8221;</p>

<p>a</p>
]]></content:encoded>
			<wfw:commentRss>http://abing.gotdns.com/posts/2007/cakephp-modifications-is-on-temporary-hiatus/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP4 Tricks: The Singleton Pattern &#8211; Part II</title>
		<link>http://abing.gotdns.com/posts/2006/php4-tricks-the-singleton-pattern-part-ii/</link>
		<comments>http://abing.gotdns.com/posts/2006/php4-tricks-the-singleton-pattern-part-ii/#comments</comments>
		<pubDate>Tue, 07 Nov 2006 14:28:07 +0000</pubDate>
		<dc:creator>nimrod.abing</dc:creator>
				<category><![CDATA[Code and Consequences]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://abing.gotdns.com/posts/2006/php4-tricks-the-singleton-pattern-part-ii/</guid>
		<description><![CDATA[In the previous article we took a look at one possible implementation of the Singleton design pattern in PHP4. In this second installation, we take a look at some possible applications for it.

In [part one][part-1], we went through the basics of the Singleton design pattern. We ended up with two classes:

An Object class that we [...]
<p>a</p>
]]></description>
			<content:encoded><![CDATA[<p>In the previous article we took a look at one possible implementation of the Singleton design pattern in PHP4. In this second installation, we take a look at some possible applications for it.</p>

<p><span id="more-70"></span></p>

<p>In [part one][part-1], we went through the basics of the Singleton design pattern. We ended up with two classes:</p>

<ul>
<li><p>An <code>Object</code> class that we can use as a base for our classes. This class takes care of object construction through a <code>__construct()</code> method as found  in PHP5.</p></li>
<li><p>A <code>SingletonInterface</code> class that we can use as a base for Singleton classes. This guarantees that we have a consistent interface for all Singleton objects in our application.</p></li>
</ul>

<h3>Simulating Namespaces</h3>

<p>One of the important things that PHP4 (and PHP5!) lacks is the concept of namespaces. If you have ever programmed in C++, C#, or Java you will be familiar with the concept of namespaces. For those who are not familiar with it, a namespace can be thought of as a named boundary within your program that can contain variables and functions. In other programming languages it is also possible for a namespace to hold classes and even other namespaces. One of the main reasoning behind the concept of namespaces is to prevent naming clashes between software libraries.</p>

<p>Using a namespace, you can create global variables under one namespace without having to worry about another global variable with the same name under another namespace. The two global variables are treated as <em>two</em> different global variables even though they have the same name.</p>

<p>Now that we have a workable implementation of a SingletonInterface, it&#8217;s time to put it to use. One of the most useful applications of a Singleton in PHP4 (and PHP5) is to create a namespace to place our &#8220;global&#8221; variables under. For example:</p>

<pre><code>class MyGlobals extends SingletonInterface {
    var $_properties = array();

    function &amp;#038;getPropByRef($propName) {
        static $_null = null;

        $_this =&amp;#038; MyGlobals::getInstance();
        if (isset($_this-&gt;_properties[$propName])) {
            return $_this-&gt;_properties[$propName];
        }
        else {
            return $_null;
        }
    }

    function getPropByVal($propName) {
        $_this =&amp;#038; MyGlobals::getInstance();
        if (isset($_this-&gt;_properties[$propName])) {
            return $_this-&gt;_properties[$propName];
        }
        else {
            return null;
        }
    }

    function setPropByRef($propName, &amp;#038;$value) {
        $_this =&amp;#038; MyGlobals::getInstance();
        $_this-&gt;_properties[$propName] =&amp;#038; $value;
    }

    function setProfByVal($propName, $value) {
        $_this =&amp;#038; MyGlobals::getInstance();
        $_this-&gt;_properties[$propName] = $value;
    }

    function __construct() {
        // Perform object initialization here.
        parent::__construct();
    }

    function &amp;#038;getInstance() {
        return parent::__getInstanceImp(&amp;#8217;MyGlobals&amp;#8217;);
    }
}
</code></pre>

<p>We define two types of setters and getters here. One type deals with references and the other type deals with values. This is important because under PHP4, object copy semantics are slightly different from PHP5. Assigning an object to another variable name in PHP4 will result in a deep copy operation. Depending on what the program is trying to do, this can lead to some unexpected results and subtle errors that are very hard to find.</p>

<p>Consequently, the notion of using a Singleton to simulate a namespace extends to the idea of &#8220;packages&#8221;. A package is a collection of related variables and functions (in other languages, they can also contain other packages as well as classes) that can be accessed using a single namespace.</p>

<p>The functions and variables in a package can be defined as <code>static</code> methods and properties of a class in other languages. In PHP4, while we do have a way of implementing <code>static</code> methods, we have no way of implementing <code>static</code> properties.</p>

<p>This next example takes the notion of simulated namespaces further by defining &#8220;static&#8221; methods. We call them &#8220;static&#8221; methods because they make use of &#8220;static&#8221; properties.</p>

<pre><code>class MyPackage extends SingletonInterface {
    var $staticProperty1;
    var $staticProperty2;

    function staticFunction1() {
        $_this =&amp;#038; MyPackage::getInstance();
        $_this-&gt;staticProperty1 = &amp;#8216;Changed some value&amp;#8217;;
    }

    function staticFunction2() {
        $_this =&amp;#038; MyPackage::getInstance();
        $_this-&gt;staticProperty2 = &amp;#8216;Changed another value&amp;#8217;;
    }

    function __construct() {
        // Perform object initialization here.
        parent::__construct();

        $this-&gt;staticProperty1 = &amp;#8217;some value&amp;#8217;;
        $this-&gt;staticProperty2 = &amp;#8216;another value&amp;#8217;;
    }

    function &amp;#038;getInstance() {
        return parent::__getInstanceImp(&amp;#8217;MyPackage&amp;#8217;);
    }
}

MyPackage::staticFunction1();
MyPackage::staticFunction2();
$pkg =&amp;#038; MyPackage::getInstance();
echo &amp;#8220;{$pkg-&gt;staticProperty1}\n&amp;#8221;;
echo &amp;#8220;{$pkg-&gt;staticProperty2}\n&amp;#8221;;
</code></pre>

<h3>Everything Else Follows&#8230;</h3>

<p>From these two basic notions, we can come up with many other ways of using the Singleton pattern in our programs. Using Singletons in place of global variables in PHP4 helps to avoid many of the security mishaps that result in the use of global variables. Although there is no silver bullet to creating a completely secure program (much less a secure program in PHP4!), completely eliminating the use of globals is a step in the right direction.</p>

<p>Using Singletons to implement &#8220;packages&#8221; allows for greater code re-use in PHP4. Although you can always create &#8220;packages&#8221; by placing all your related functions and globals in one file, you have to contend with naming conflicts as your program grows or as you rely on more and more third-party libraries.</p>

<p>As I have said above, you can extend on the basic notion of the namespace and packages and use the Singleton design pattern to implement the following:</p>

<ul>
<li><p><strong>Centralized configuration object</strong> &#8211; all the configuration variables and properties that should be accessible during the lifetime of your program can be in one place. This makes it easier to debug your application and it also simplifies the process of performing audits.</p></li>
<li><p><strong>Wrapping superglobals with an object</strong> &#8211; although not really necessary, wrapping superglobals such as <code>$_SERVER</code>, <code>$_REQUEST</code>, and <code>$_COOKIES</code> into a singleton can be useful when building a library. You can abstract away the details of where these values are coming from and at the same time, you can perform filtering on incoming superglobal values.</p></li>
<li><p><strong>Maintain several database connections</strong> &#8211; for small to medium-sized applications, a single database connection to a single server will normally suffice. For larger, enterprise-level applications however, you may need to connect to more than one database server.</p></li>
<li><p><strong>Create an &#8220;object factory&#8221;</strong> &#8211; a more advanced use case would be to use a Singleton as an object factory. An object factory takes care of instantiating and initializing objects from many different classes and hands them off to the client code. Consequently, objects created by the factory are &#8220;registered&#8221; into an internal object registry allowing the client code to re-use an instance of an object. The SingletonInterface class is one example of such a factory.</p></li>
</ul>

<p>Code re-use, security, and overall ease of maintenance. These are just some of the benefits of using a Singleton in your programs. If you find other uses for this code, or if you have any corrections to make, please post your comments. Please note that I reserve the right to select or reject comments for publishing.</p>

<p>[part-1]: /posts/2006/php4-tricks-the-singleton-pattern-part-i/ &#8220;PHP4 Tricks: The Singleton Pattern &#8211; Part I&#8221;</p>

<p>a</p>
]]></content:encoded>
			<wfw:commentRss>http://abing.gotdns.com/posts/2006/php4-tricks-the-singleton-pattern-part-ii/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Lazy Loaded Models for CakePHP</title>
		<link>http://abing.gotdns.com/posts/2006/lazy-loaded-models-for-cakephp/</link>
		<comments>http://abing.gotdns.com/posts/2006/lazy-loaded-models-for-cakephp/#comments</comments>
		<pubDate>Sun, 05 Nov 2006 16:02:38 +0000</pubDate>
		<dc:creator>nimrod.abing</dc:creator>
				<category><![CDATA[CakePHP]]></category>
		<category><![CDATA[Code and Consequences]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://abing.gotdns.com/posts/2006/lazy-loaded-models-for-cakephp/</guid>
		<description><![CDATA[I have been doing some recent profiling on CakePHP, the results look good despite the large amount of bootstrap code that it has to run with each request. However, I have observed one thing about the framework that could pose problems on servers with heavy traffic: the bootstrap process loads model class files even if [...]
<p>a</p>
]]></description>
			<content:encoded><![CDATA[<p>I have been doing some recent profiling on CakePHP, the results look good despite the large amount of bootstrap code that it has to run with each request. However, I have observed one thing about the framework that could pose problems on servers with heavy traffic: <em>the bootstrap process loads model class files even if the models are not used in the duration of the request.</em></p>

<p><span id="more-68"></span></p>

<p>Why would this be a problem? Depending on the PHP setup, either CGI binary or Apache module, the server could end up exhausting file handles under heavy traffic. This issue is even worse on a virtual hosting setup. Virtual hosting allows one to run a website for cheap by sharing a server with several other websites. Because of this shared environments, there is the increased risk of file handle exhaustion leading to failed requests not only for the CakePHP-based website, but for the other hosted websites as well.</p>

<p>CakePHP, by default, loads everything it finds in the <code>app/models</code> directory into memory: even if it&#8217;s not used for the duration of the request. The only reason I see why this is done is to ensure that associations work automagically. However, simply loading everything into memory can be wasteful. It wastes memory and processing time because the PHP engine has to load and parse all those files, even if most of it is &#8220;dead code&#8221; anyway. While this is not a problem in most setups, I have seen hosting services where they do &#8220;CPU utilization capping&#8221;.</p>

<p>As part of my ongoing project to improve on CakePHP to allow for porting of my old framework, I have decided to implement a modification that allows for lazy-loaded models in CakePHP. The modification has two goals in mind:</p>

<ol>
<li>Allow client code that depends on the mainstream CakePHP to work without problems;</li>
<li>Consequently, this allows the programmer to decide what gets to be loaded on each and <em>every</em> request and what gets to be lazy-loaded.</li>
</ol>

<p>To allow for goal number 1, I had to leave the bootstrap code alone. For number 2, I had to modify the way CakePHP models are instantiated from both the controller and the models themselves. The controller instantiates the appropriate model at runtime. A model <em>may</em> instantiate one or more models from its associations model. But how do you do lazy-loading and still allow for the old model loading behavior?</p>

<p>My solution is to create a new directory under the <code>app/models</code> directory called <code>lazy_load</code>. All models to be lazy_loaded will be placed here. Everything else can stays in <code>app/models</code>.</p>

<p>A new function had to be created to perform the task of lazy loading. The <code>lazyLoadModel()</code> function in the <code>basics.php</code> file takes care of the task. It behaves a fashion similar to <code>loadModel()</code> by loading models from the <code>lazy_loaded</code> directory found in the <code>modelPaths</code>.</p>

<h3>Show Me The Code</h3>

<p>The changeset for this modification can be found [here][cs-1]. This should apply cleanly to CakePHP version 1.1.8.3544. It should also apply cleanly to version 1.1.10.3825. If you are still using 1.1.8.3544, then you should upgrade to 1.1.10.3825 <em>before</em> applying this patch. Otherwise, you will end up having to manually resolve conflicts. Of course, if you apply this modification, you will end up having to re-apply it with each new version of CakePHP.</p>

<h3>Does it work?</h3>

<p>I have done a bit of profiling on an example app based on the [Blog tutorial][cake-blog-tut] from the CakePHP Manual as well as tests using [Siege][joedog-siege]. For this test, I created 10 dummy model class files and placed them under the <code>app/models</code> directory as usual and then I ran the profiler from my demo version of Zend IDE. As expected, CakePHP loads everything it can find under the <code>app/models</code> directory and chews up processing time, memory and file handles. The Zend IDE profiler reports that it had to open at least 50 files for the blog app home page.</p>

<p>With Siege, with 100 concurrent requests and with 10000 reps per connection (resulting in 1,000,000 hits total), the server began to cave after the first 4,000 hits and continued to slowdown to at most 40 to 70 seconds on a lot of requests. I was not sure if there were any file handle exhaustion errors since Siege is not able to display the actual page that it requested.</p>

<p>For the second test, I moved all the dummy classes from <code>app/models</code> to <code>app/models/lazy_load</code> I also did the same for the classes that are actually used by the app (post.php and tag.php). First the Zend IDE profiler reports only 40 files are being opened for each request. With Siege, under the same settings as before, the server was able to make it through the ordeal slowing down to 10 to 20 seconds on some requests after about 700,000 hits.</p>

<p>For me, it&#8217;s a significant improvement. But you don&#8217;t have to take my word for it so go do your own tests and let me know about your results.</p>

<h3>Caveats</h3>

<p>This is a modification on the mainstream CakePHP code. Which means if anything changes on the mainstream, this modification may also be affected. If you apply the patch to future versions of CakePHP and it results in failed hunks, then you should check what went wrong and take the necessary steps to correct the problem.</p>

<p>Theoretically, the lazy loader should work for plugins too. But I have not tried it yet.</p>

<h3>Conclusion</h3>

<p>If you like this modification and use it in your production site, please leave a comment here and let me know what you think.</p>

<p>This and other modifications I am making are being made independently from the CakePHP project. As such, you should <em>never</em> report problems you encounter with my modifications to either the CakePHP mailing list or IRC channel. Please report them directly to me.</p>

<p>If you want to send bug fixes or suggestions for improvement, please send email to:</p>

<p>&#110;&#105;&#109;&#114;&#x6F;&#x64;&#x2E;&#x61;&#98;&#105;&#110;&#x67;&#43;&#x62;&#x6C;&#111;&#103;&#x40;&#103;&#109;&#97;&#105;&#x6C;&#x2E;&#x63;&#111;&#x6D;</p>

<p>Please use the subject line:</p>

<p>PATCH: CakePHP Model Lazy Loader</p>

<p>[cs-1]: http://abing.gotdns.com/cake/diffs/000010-lazy-loaded-models.diff &#8220;Changeset for lazy loaded models in CakePHP&#8221;
[cake-blog-tut]: http://manual.cakephp.org/appendix/blog_tutorial &#8220;CakePHP Blog Tutorial&#8221;
[joedog-siege]: http://www.joedog.org/JoeDog/Siege &#8220;JoeDog.org: Siege&#8221;</p>

<p>a</p>
]]></content:encoded>
			<wfw:commentRss>http://abing.gotdns.com/posts/2006/lazy-loaded-models-for-cakephp/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
