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

  1. 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.

  2. I could implement this where I need it. BUT this means I have to implement it countless times in independent projects.

  3. I could use a trait, if I was not stuck with PHP 5.3. Not an option for me.

  4. 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?

  • Why not simply implement it as a class? Like your Tree example. (new Tree( $myArray))->get('vendor\product\...') – K.. Jan 23 '13 at 12:27
  • I do not see how this is better than using a static method. I still have the same amount of coupling. So why bother creating an instance? – Oliver A. Jan 23 '13 at 13:02
  • Ah I see... my thought was you just disliked static methods. – K.. Jan 23 '13 at 13:43

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 Jan 31 '13 at 19:28
  • @RobertHarvey true :) – Eloff Jan 31 '13 at 19:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.