Archive for the ‘PHP’ Category.

PHP 5.3 and Closures

I'm fairly excited because as of only a week or so ago I found the closures rfc, and not only did I find that the rfc has a working patch, apparently it's already in PHP 5.3.

You see, apparently it's not good enough that we get name spaces and late static binding, oh no, we get closures too!

I downloaded the Win32 snapshot from PHP snapshots page and indeed, closure support was included.

 
<?php
$closure = function ($args) use ($global) { /*Body*/ };
?>
 

According to the rfc, one must manually define external variables used within a function, however in my own tests you can still use the global keyword. The difference between the two is the use statement preserves the value of $global at creation and the global keyword would work as you would expect it to with a normal function. For example:

 
<?php
$global = "Global Variable";
 
$closureUse = function ($arg) use ($global) { echo $global . " - " . $arg; };
$closureGlobal = function ($arg) { global $global; echo $global . " - " . $arg; };
 
echo "Basic Closure Tests\n";
echo "-------------------\n\n";
 
echo "\$closureUse('test'): ";
$closureUse('test');
echo "\n";
 
echo "\$closureGlobal('test'): ";
$closureGlobal('test');
echo "\n";
 
echo "\n";
echo "Global Closure Tests\n";
echo "--------------------\n\n";
 
$global = "Global Variable (Changed)";
 
echo "\$closureUse('test') (changed \$global): ";
$closureUse('test');
echo "\n";
 
echo "\$closureGlobal('test') (changed \$global): ";
$closureGlobal('test');
echo "\n";
?>
 

Would output:

 
Basic Closure Tests
-------------------
 
$closureUse('test'): Global Variable - test
$closureGlobal('test'): Global Variable - test
 
Global Closure Tests
--------------------
 
$closureUse('test') (changed $global): Global Variable - test
$closureGlobal('test') (changed $global): Global Variable (Changed) - test
 

You can, as well, return references with a closure by putting the & between the function keyword and the parenthesis.

 
<?php
$closureReturnsReference = function & ($args) use ($global) { /*Body*/ };
?>
 

Just one of many shiny fancy things to look forward to in PHP 5.3.

Edit 7/23/2008:

I should mention to the people that trashed my examples on reddit, I'm sorry for assuming you knew what closures were and the the real world uses of them. I will try to refrain from giving a concise example of how a new language feature interacts with existing features and conventions, especially in PHP where things are a bit disorganized.

Hierarchical Data With PHP and MySQL

I recently had fun with an all-to-common issue with SQL driven websites: hierarchical data. For those who don't like big words, think trees. Other people have already discussed storage methods, and I would actually highly suggest you read the writeup if you haven't already.

While it is fairly straightforward to deal with, in our case we use HTML_QuickForm to handle our forms and are using QuickForm's hierselect to select a category.

The issue starts showing its face in 2 distinct areas: (1) the client is not yet sure how deep they need their categories to go, and (2) the hierselect requires a very specific format of data to be passed in.

Continue reading ‘Hierarchical Data With PHP and MySQL’ »

*AMP and Runaway Scripts

Peter Zaitsev posted a very interesting test on how PHP and Apache handle runaway PHP scripts.

I'm sure all of us have had a long executing SQL script or at least a runaway script, and he points out even with ignore_user_abort set to FALSE and max execution times set both in PHP and Apache, a runaway SQL query can execute beyond the timeouts, even when aborted by the user (stop button on the browser).

Even using the function connection_aborted() to check for a user abort fails.

However, the script will cease on a user abort if it performs regular ob_flush(); flush(); commands. For example:

<?php
echo("Hello");
for($i=0;$i<10000;$i++)
{
	sleep(1);
	echo('.');
	ob_flush();
	flush();
}
?>

Just one more reason why I love the MySql Performance Blog.

Automating the Development Workflow

I just rolled out some new automation tools for a few projects here at work and so far I've been extremely happy.

Much to my embarrassment, development has previously been outside of source control due to the fact that we develop sites, we don't deploy packaged applications, and we don't have a cohesive IT setup (everyone sets up their desktop to their liking so maintaining consistent development environments across all computers is difficult).

However, thanks to SVN, Xinc and Phing (and DBDeploy), this has changed! Now everything is in source control and automatically deployed to our dev server upon commit. I am currently talking with Arno about perfecting svn tag monitoring to automate staging and (possibly) live deployments, so I'll post about what I did when that's finished.

The great thing about this setup is all pieces are technically interchangeable. If you don't like Xinc you can use CruiseControl. If you don't like Phing you can use Pake, or a shell script even. If you don't like DBDeploy you can roll your own setup or swap it out for your database versioning system of your choice!

However this post will cover Xinc, Phing, and DBDeploy as (a) I have experience with them and none of the others, and (b) they integrate extremely well (Xinc and Phing's primary distribution method of choice are PEAR channels).

Continue reading ‘Automating the Development Workflow’ »

Partial Classes in PHP

One of my favorite features of C# is Partial Classes. For the uninitiated, it is a way of defining a class in two separate locations. Very useful when you have code generation utilities such as LINQ.

Unfortunately, PHP has no such feature (though if anyone's listening it would be a great feature to add to the PHP6 feature list), however thanks to the magic of __call($method, $args), __get($key), and __set($key, $value) overload functions as well as passing by reference (aah the good ol' &) we can imitate partial classes.

The idea behind this partial class hack is to instance a copy of the partial class in question and have our magic functions forward any undefined requests to the partial class.

The partial class (probably with the naming convention Partial_CLASSNAME) will contain a reference to the main class and also have magic functions forwarding undefined requests to the main class. The reason why we have our magic functions in the partial class is so that any internal references can still be made (methods in Partial_CLASSNAME must have access to the methods and members in CLASSNAME).

The constructor in the main class will automatically seek out the partial class (and additional coding can be done to seek out more than 1 partial class as well as do some integrity checking) so that the programmer does not have to intervene to form the 'full class'.

Continue reading ‘Partial Classes in PHP’ »

Pro PHP

My copy of Pro PHP: Patterns, Frameworks, Testing and More by Kevin McArthur has already been worth the money I spent on it.

In our, albeit slow, upgrade to more modern development practices (code version and unit testing being the last elements on my list), I was particularly fearful of code versioning namely concerning issues of automating a build process to export a copy of the repository to our shared development server, or just have a local server installed for everyone one.

However Chapter 8 has pointed me to two programs that I sincerely regret not having heard of until now: Phing and Xinc.

Phing is a build system written in PHP that works extremely well with PHP and PHPUnit. You can configure your own build targets, for example like "get" (SVN update essentially), "test" (run PHPUnit or any other unit testing), "try" (copy to a development server), and "deploy" (copy to your live server).

Xinc is a continuous integration server. Essentially, it monitors an SVN repo and performs a user defined action (usually running a phing buildscript) on any changes to the repo. Which is awesome because its solves the issue of updating the dev server. Having Xinc run a > phing try on SVN updates is exactly what we need! I'm even having delusions of grandeur of having it monitor tags for doing live deployments as well.

Don't take my word as gospel, I haven't actually installed and tested these systems out, but when I do you can rest assured I will be writing about it.

Updates and ::’s

In my previous article (Microsoft Access and PHP), I discussed getting mdbtools setup and dynamically interacting with a instance of mdb-sql. Well it turns out somewhere in the pipeline (probably mdb-tools), we're either not getting an EOF or reading an EOF right and as such I can read lines from the program's STDOUT stream, but as soon as I hit the end of the output my script hangs indefinitely waiting for something and all my attempts at detecting an EOF failed. Sorry to disappoint.

On lighter news, my coworker got the greatest error ever:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM

Turns out according to these guys it's Hebrew and refers to the double colon (::) operator.

Right...

Microsoft Access and PHP

Microsoft products can really be a big wrench in the finely oiled machine that is your development environment. While Microsoft does offer some excellent products and development tools, when you work from an open source context, these great tools become great hazards and headaches.

Case in point, access databases. Take as a recent example, a client that gets its data from a third party. That data comes in a Access (.mdb) format, probably convenient for the producing company as well as the assumption that chances are very likely that the person receiving the data will be able to read it (due to the widespread availability of Microsoft Office).

Importing said .mdb in PHP is not so nice or convenient, that is if you aren't running your server on Windows (which chances are you aren't). In Windows you merely need to either create an ADO object (or use ADODB), or use COM to communicate with a local install of Microsoft Office to trigger an export. In Linux, neither of those choices are even available. However we thankfully have some good command line utilities, for example: MDB Tools. (Tip: Check out a copy from CVS if 0.5 is segfaulting on your database)

In addition to some unixODBC drivers, it provides some very nice command line utilities like mdb-tables (which prints the tables in a .mdb file), mdb-schema (which prints the schema for all or a specific table), mdb-export (which produces a CSV output of a specific table in the .mdb), and mdb-sql (which provides a subset of SQL interface to the .mdb file). All of these tools come together to form a very nice tool set to import a .mdb file.

Fun things however, as I was working on my import script (I was just using simple exec() commands and getting full output and parsing from there), I decided to play around with stream programming and provide an interface to mdb-sql using proc_open() to make the import less memory intensive. I ran into some snags using fgets() on the STDIN stream and when I solve those I'll post my code and a tutorial.

OO Design and PHP

I was helping a coworker the other day with some object oriented design issues in PHP and thought it would be great to share with the general PHP community as the general PHP community seems to lack in good OOP skills.

The task, which will be detailed later when we release it, boiled down to having a collection of files we needed to perform an operation on. Sometimes the entire collection, sometimes just a subgroup. Currently the system will only support 1 kind of file however in the very near future a new file will be added. My coworker tackled it well but a few problems that I helped him out with. Namely he made a few common mistakes in the design that most PHP developers make, namely being inconsistent with naming/etc. and not utilizing Interfaces and argument type-hinting to enforce good design, as well as putting logic in the wrong classes.

One of the few pitfalls that did happened was placing the render() function in the collection class. While this would not be a problem for a single type, when extending the system to handle n node types we come across unnecessary complexity issues in adding to the render() function, as well as making it nigh-impossible to keep the original includes intact (so as to make upgrades work without the hassle of merging code).

Continue reading ‘OO Design and PHP’ »

PHP Feeds, or, Get Your Read On!

I've started to amass a large amount of feeds in my reader and I thought I'd share a few with you:

PHPDeveloper.org (feed)

Great aggregation of blog posts and updates in the PHP world.

Zend Developer Zone (feed)

Zend's place for all things PHP related

SitePoint.com (blogs) (articles)

The infamous SitePoint. Not entirely PHP, but excellent web related articles and a good way to keep loose tabs on the other web spheres (ASP.NET and RoR in particular)

Particletree (feed)

Doesn't update very often, but each article is a gem (in terms of solving a programming problem).

Chris Shiflett (feed)

THE PHP and Web Application Security guy.

Joel on Software (feed)

A classic, not really PHP oriented.

And finally, definitely not PHP focused, but a very good blog to read if you do any MySQL work (if you are a PHP person, chances are this includes you)

MySQL Performance Blog (feed)

Great collection of articles and talks on optimizing MySQL, either at the server or query level, and more...

While this isn't all of the feeds I have on programming related topics, some of them are new adds and I want to give it some time before I share the links.