Daily Archive for September 2nd, 2009

Left to the reader

PHP best practices have been moving steadily towards putting all functions inside classes, if only to provide namespacing. The good news is that you have no more namespace collision issues (well, unless you join together two projects with different conventions), and the bad news is that your function names are starting to get quite long.

<?php echo Framework_Html::Escape($username); ?>

Escaping strings to be output in HTML documents is a quite common behavior in PHP websites. Is the risk of a name collision worth giving up on a shorter approach, like:

<?=esc($username)?>

I am a proponent of turning very common operations into short functions with appropriate “smart” behavior. For instance:

  • esc(string $string) returns a Framework_Html instance representing the string escaped with htmlspecialchars.
  • esc(Framework_Html $html) returns its argument as-is, so you don’t have to care about whether a given string has already been escaped or not.
  • esc($format, $a, $b, $c...) returns a Framework_Html instance representing the unescaped string sprintf($format, esc($a), esc($b), esc($c)), useful to avoid repeated escaping in, say, <a href="%s">%s<a/> .

In a similar vein:

  • func(callback $call) returns its argument (after checking that is_callable($call) is true). This serves as a piece of documentation to tell that something is a function.
  • func(object $obj, string $func) returns a callback representing the member function $func of object $obj.
  • func(string $class, string $func) returns a callback representing the static member function $func of class $class.
  • func(string $args, string $body) acts as a shorter alias for create_function.
  • func(string $body) acts as an alias for create_function('$_',"return $body;"), in those cases you need a very short lambda expression.

And of course, there’s the jslog() and is() functions discussed earlier on the blog.

I think there would be a small handful of functions, maybe 8 or 10, that would be used so often on a given project that everyone would have to know about them anyway—so, you might as well keep them out of any class.



1150 feed subscribers
(readers who polled a feed this week)