The Problem
I regularly find myself writing the same code over and over again.
For example if I want a value from a nested array structure I end up writing something like this:
$config = function_to_get_nested_array();
$node = $config;
foreach(array('vendor','product','config','leave') as $index => $key){
if(! isset($node[$key])){
//throw exception
}
$node = $node[$key];
}
I would prefer to have something like
$config = function_to_get_nested_array();
$node = get_node($config, 'vendor/product/config/leave');
But how do I implement it?
Possible Solutions
I could implement a function as I did above. BUT my packages heavily rely on autoloading and are purely OO. Right now I just have to clone an submodule in the right directory and everything works fine.
I could implement this where I need it. BUT this means I have to implement it countless times in independent projects.
I could use a trait, if I was not stuck with PHP 5.3. Not an option for me.
I could implement a static service provider.
For various reasons static classes and methods are usually a bad choice, but I am tempted to do so in this case.
use vendor\product\helpers\ArrayTree as Tree
...
$config = function_to_get_nested_array();
$node = Tree::getNode($config, 'vendor/product/config/leave');
Looks very tempting, because it supports autoloading and namespaces.
The Question
Is there a better solution to implement this kind of helper functions?
1 Answer 1
This is a good scenario to use a static method.
Static methods can be problematic since they are essentially global functions, i.e. the call is hard wired to that specific class. During unit testing it is hard to replace a static method with a mocked one.
However, in your case, getNode
is a pure stateless utility function. Go ahead and implement that tempting solution.
class ArrayTree {
public static function getNode($array, $path) {
...
}
}
-
2
it is hard to replace a static method with a mocked one
-- You don't have to, if you never hold state or cause side effects.Robert Harvey– Robert Harvey01/31/2013 19:28:01Commented Jan 31, 2013 at 19:28 -
(new Tree( $myArray))->get('vendor\product\...')