开发者

Methods of reusing error messages

We are using PHP 5.3 and Zend Framework for 开发者_如何学JAVAa large project, and I've run into a problem of convenience. We reuse the same error messages over and over again in different parts of the application, like "You don't have permission to complete this action." Does anyone have any unique ways of reusing error messages so we don't have to rewrite them over and over again?

My first thought was to do something simple like this:

class ErrorMessage
{
    const ERROR_NO_PERMS = 'noPerms';
    const ERROR_INT = 'int';

    protected static $_messages = array(
        self::ERROR_NO_PERMS => 'You do not have permission to complete this action',
        self::ERROR_INT      => "'%s' must be an integer",
    );

    public static get($errorCode)
    {
        if (!array_key_exists($errorCode, self::$_messages)) {
            // error
        }

        // check for translation

        return self::$_messages[$errorCode];
    }
}

What would you do? (Keep in mind that we would like this to be integrated with ZF, so we are open to any ideas that extend into native ZF classes.)


You could also created "named exceptions".

class PermissionException extends Exception
{
  public function __toString()
  {
    return 'You do not have permission!';
  }
}

If ZF has own exceptions, you can extend those. Or you can extend one of the already available PHP exceptions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜