Search code examples
phpoopfunctional-programmingcode-organization

Procedural dependencies in an OOP application


Despite the number of similar questions, I haven't yet managed to find any such concrete answer (or at least a strongly opinionated individual)

I've (at this time) decided to use "helper" classes, which are simply aggregates of static methods in a class, fittingly named String for example. The class itself has no prospect of being an object instance, and has no reason to.

Now I've noticed many people consider this abuse. I do too, and have only resolved to maintain this approach for the benefits of code organization and (more importantly) auto-loading.

String::keysplode('|', 'apple|banana|coconut', array('a', 'b', 'c'));

Here we have keysplode(). It performs explode() on the given string, with the given delimiter, then calls trim() on each element. The resulting array is passed with the array argument to array_combine(). The result?

array('a' => 'apple', 'b' => 'banana', 'c' => 'coconut');

Great! Fancy! Who cares?

The point is, this function really doesn't belong in a class. Right now it lives at \Package\Common\String::keysplode(), and while that's a nice place for it, I can see how that is considered "abuse".

I have a plethora of these functions, ones that belong in the array_* or str_* pseudo-namespace, and elsewhere. The further problem is, my "genuine" classes, ones that leverage OOP correctly (or so I believe) use these functions intimately.

The "question", as it were, is where should functions like this go?

When we create functions that extend the "core" functionality of a language, where do we put these functions? Furthermore, how do we manage the dependencies created upon the functions by other parts of an application?


Solution

  • Putting library functions into a static class has been a PHP idiom because PHP lacked namespaces and the syntax for static methods is similar to the syntax for accessing package functions in Perl.

    Now that PHP has namespaces, the clear answer is to put these methods into namespaces (and no longer static classes). While I think that this will be a slow transition (because so many people are still not on PHP 5.3, and many people are on shared hosts), the adjustment is readily apparent and hopefully framework and library developers accept this new idiom (which is standard for other languages with namespaces like C# and Perl).

    <?php
    
    namespace Foo;
    
    function foo () {
        echo 'foo';
    }
    
    namespace Bar;
    
    use Foo;
    
    Foo\foo();