php - Implementing my own utility functions in Lithium? -
i newbie lithium php , know basics of lithium. want implement own utility
functions. have created utilities
folder parallel app\controllers
. how class looks like:
<?php namespace app\utilities; class utilityfunctions { protected $_items = array( 'a' => 'apple', 'b' => 'ball', 'c' => 'cat' ); //i _items undefined here, blame poor oop skills. public function getitem(alphabet) { return $this->_items[alphabet]; } } ?>
i use in 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 right way it? utility class need extend something? or lithium provide other way achieve this?
moreover, not able access protected variable $_items
in getitems
method. had same thing implemented in controller , worked fine then.
this fine way it. there 2 core lithium classes extend from: \lithium\core\object , \lithium\core\staticobject
i think not necessary use case.
the reason cannot access protected variable because invoking method statically. should rewrite class use static variables , methods. also, assume it's typo creating example stackoverflow, forgot $
alphabet
var in 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 not change utilityfunctions class, instead instantiate class in 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 simple case class not need hold state, recommend static methods. take @ php manual little more info on static keyword.
another minor note, not need leading backslash in use
statement.
Comments
Post a Comment