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 aFramework_Htmlinstance representing the string escaped withhtmlspecialchars.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 aFramework_Htmlinstance representing the unescaped stringsprintf($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 thatis_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$funcof object$obj.func(string $class, string $func)returns a callback representing the static member function$funcof class$class.func(string $args, string $body)acts as a shorter alias forcreate_function.func(string $body)acts as an alias forcreate_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.
Hi. I'm Victor Nicollet,
Recent Comments