Uncategorized

Recently I started to write my CodeIgniter helper’s to use classes with static methods instead of writing global functions. This stops from having to check if the function name you are about to use already exists, and also allows the use of PHP namespaces if you desire.

Here is a example of how the helper functions are normally setup:

    if( !function_exists('longUniqueString')) {
            /**
          * Provides an extra long random unique String
          * 
          * @param $iterations (default 3)
          * @return String
          *          Random String
          */
         function longUniqueString($iterations = 3) {
             get_instance() -> load -> helper('string');
             $s = '';
             for($i = 0; $i < $iterations; $i++) {
                 $s .= random_string('unique');
             }

             return $s;
         }
    }

Here is the static method way of doing the same thing:

    class CMUtils {


        /**
         * Provides an extra long random unique String
         * 
         * @param $iterations (default 3)
         * @return String
         *          Random String
         */
        public static function longUniqueString($iterations = 3) {
            get_instance() -> load -> helper('string');
            $s = '';
            for($i = 0; $i < $iterations; $i++) {
                $s .= random_string('unique');
            }

            return $s;
        }
    }

The name of the php helper file can be anything you want. Let’s say this particular helper was called utils_helper.php . The code to call the helper would go something like this

    $this -> load -> helper('utils');
    $myStr = CMUtils :: longUniqueString();