Standardized way of interpolating variables into PEAR_Exception messages?
| From: | Dan Scott | Date: | Sat, 23 Sep 2006 15:04:03 +0000 |
| Subject: | Standardized way of interpolating variables into PEAR_Exception messages? | ||
| Groups: | php.pear.dev | ||
| Request: | Send a blank email to pear-dev+get-44012@lists.php.net to get a copy of this message | ||
Hello:
While working through my PEPrs, I converted my PEAR_ErrorStack
error-handling to PEAR_Exception in accordance with the RFC for
error-handling in PHP 5 packages. But one thing that I seem to have
lost in the conversion is the ability to interpolate variables into
the messages that I pass to PEAR_Exception. I was looking for
something akin to the PEAR_ErrorStack templates.
Currently, it seems like every package is responsible for its own
interpolation -- so a typical usage would be something like:
if ($var < 0) {
throw new Foo_Exception("The value of VAR cannot be '$var'.");
}
The problem with this approach is that it becomes very difficult to
internationalize the message strings -- which is why, in my definition
for File_MARC_Exception near the bottom of
http://marc.coffeecode.net/highlight_MARC.php, I've defined the error
codes as class constants and a static array of messages with the error
codes as the keys to the array.
However, I'm currently going to have to reimplement PEAR_ErrorStack's
variable interpolation, or some variation on it, in my own packages.
So the code will look something like:
if ($var < 0) {
$message = Foo_Exception::interpolateMessageVariables(Foo_Exception::$message[Foo_Exception::ERROR_VAR_BAD],
$var);
throw new Foo_Exception($message, Foo_Exception::ERROR_VAR_BAD);
}
... but I can't be the only person facing this problem. It seems to me
that it would make sense to provide a standardized solution for the
problem as part of the PEAR_Exception class, and to include some
examples of best practices in the package's accompanying
documentation.
I initially thought the ideal place to enable this would have been in
the constructor (something like testing the first parameter to see if
it's an array; if so, then treat the first element as the message
string and any following elements as variables to be interpolated) but
I can see that the constructor arguments are already overloaded.
I'm open to someone telling me that I've understood PEAR_Exception all
wrong, and would love to hear that there's an easy solution to the
problem.
Ah... and I've just been told on IRC that the RFC requiring
PEAR_Exception for PHP5 packages, although "approved", is not
necessarily a requirement after all. It might be nice to edit
"approved...but despite that, not agreed upon or required" proposals
to reflect their true status. I'm just trying to strictly follow all
of the coding standards for my proposals as best I can.
Dan