Helper class for Zend Framework apps

Maybe it’s because I got my ZF start from Magento, but I’m enamoured with having a static class full of global helper methods.

For example:

/**
* Get the user's real IP address through proxies
*
* @return string
*/
public static function getIpAddress() {
    // Gets the user's real IP address
    if ( isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
        $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        return trim($ips[count($ips) - 1]);
    } elseif ( isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP']) ) {
        return $_SERVER['HTTP_CLIENT_IP'];
    }
    return $_SERVER['REMOTE_ADDR'];
}

Create the class file

I created my class file next to my bootstrap in /path/to/app/root/application/Base.php and put the following at the top of Bootstrap.php:

require_once(APPLICATION_PATH . DIRECTORY_SEPARATOR . 'Base.php');

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    ...

…voila! Instant application to static helper methods anywhere.

Example class

Here is an example from my Base.php file:

getRequest()->getControllerName();
    }

    /**
     * Shortcut to return the current controller name.
     *
     * @return Zend_Session_Namespace
     *
     * @since 0.0.1
     */
    public static function getSession($namespace = null) {
        if(is_null($namespace)) {
            $namespace = 'global';
        }
        if(is_null(self::$_sess) || !isset(self::$_sess[$namespace])) {
            self::$_sess[$namespace] = new Zend_Session_Namespace($namespace);
        }
        return self::$_sess[$namespace];
    }

    /**
     * Translates a camel case string into a string with underscores
     * (e.g. firstName -> first_name)
     *
     * @param string $str string in camel case format
     * @return string $str translated into underscore format
     */
    public static function fromCamelCase($str) {
        $str[0] = strtolower($str[0]);
        $func = create_function('$c', 'return "_" . strtolower($c[1]);');
        return preg_replace_callback('/([A-Z])/', $func, $str);
    }

    /**
     * Translates a string with underscores into camel case
     * (e.g. first_name -> firstName)
     *
     * @param string $str String in underscore format
     * @param bool $capitalise_first_char if true, capitalise the first char
     * in $str
     * @return string $str translated into camel case
     */
    public static function toCamelCase($str, $capitalise_first_char = false) {
        if($capitalise_first_char) {
            $str[0] = strtoupper($str[0]);
        }
        $func = create_function('$c', 'return strtoupper($c[1]);');
        return preg_replace_callback('/_([a-z])/', $func, $str);
    }

    /**
     * Get the user's real IP address through proxies
     *
     * @return string
     */
    public static function getIpAddress() {
        // Gets the user's real IP address
        if ( isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
            $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            return trim($ips[count($ips) - 1]);
        } elseif ( isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP']) ) {
            return $_SERVER['HTTP_CLIENT_IP'];
        }
        return $_SERVER['REMOTE_ADDR'];
    }

}

All that’s missing is a cleve name like “Mage”. Mine is pragmatically called Base. Not really catchy, but typing Bob::getSession() all day would cease to be cute.

(P.S., props to Paul Ferrett for the toCamelCase / fromCamelCase methods!)

Advertisements

3 thoughts on “Helper class for Zend Framework apps

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s