Search code examples
phpoopmodel-view-controllerweblithium

Implementing my own utility functions in Lithium?


I am a newbie to Lithium PHP and know the basics of Lithium. I want to implement my own Utility functions. I have created the utilities folder parallel to app\controllers. This is how my class looks like:

<?php

namespace app\utilities;

class UtilityFunctions {
    protected $_items = array(
            'a' => 'Apple',
            'b' => 'Ball',
            'c' => 'Cat'
        );

    //I get _items as undefined here, blame my poor OOP skills.
    public function getItem(alphabet) {
        return $this->_items[alphabet];
    }
}

?>

I use it in my controller as:

<?php

namespace app\controllers;

use \app\utilities\UtilityFunctions;

class MyController extends \lithium\action\Controller {
    public function index() {
        $args = func_get_args();
        $item = UtilityFunctions::getItem($args[0]);

        return compact('item');
    }
}

?>

Is this the right way to do it? Does my utility class need to extend something? Or does Lithium provide some other way to achieve this?

Moreover, I am not able to access the protected variable $_items in my getItems method. I had the same thing implemented in my controller and it worked fine then.


Solution

  • This is a fine way to do it. There are two core Lithium classes that you could extend from: \lithium\core\Object and \lithium\core\StaticObject

    I think that is not necessary for your use case.

    The reason you cannot access the protected variable is because you are invoking the method statically. You should probably rewrite your class to use static variables and methods. Also, I assume it's just a typo creating an example for StackOverflow, but you forgot the $ for the alphabet var in the getItem method.

    <?php
    
    namespace app\utilities;
    
    class UtilityFunctions {
        protected static $_items = array(
            'a' => 'Apple',
            'b' => 'Ball',
            'c' => 'Cat'
        );
    
        public static function getItem($alphabet) {
            return static::_items[$alphabet];
        }
    }
    
    ?>
    

    The other option is to not change the UtilityFunctions class, but instead instantiate the class in the controller:

    <?php
    
    namespace app\controllers;
    
    use app\utilities\UtilityFunctions;
    
    class MyController extends \lithium\action\Controller {
        public function index() {
            $args = func_get_args();
            $utilities = new UtilityFunctions();
            $item = $utilities->getItem($args[0]);
    
            return compact('item');
        }
    }
    
    ?>
    

    For a simple case like this where the class does not need to hold any state, I would recommend the static methods. Take a look at the php manual for a little more info on the static keyword.

    Another minor note, you do not need the leading backslash in your use statement.