PHP

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();

0 1914

Thought I would share a function I wrote to convert property from an a array of objects to a one dimensional array. I ran into this problem because I wanted to select a single field from a DB query into a one dimensional array. I could not figure out how to get that from the DB. All that was available was a object array or array of arrays.

Here is a function to take care of this issue

function objects_to_one_dim($array, $property) {
            $oneDimArray = array();
            foreach($array as $o) {
                $oneDimArray[] = $o -> $property;
            }

            return $oneDimArray;
}

and can be utilized like this

 $newArray = objects_to_one_dim($myObjArray, 'a_property_in_the_object');