Search code examples
phpoopnamespaceslibrariescode-organization

Is it ever okay to have a class as a collection of methods and no properties?


I'm writing a bunch of generic-but-related functions to be used by different objects. I want to group the functions, but am not sure if I should put them in a class or simply a flat library file.

Treating them like a class doesn't seem right, as there is no one kind of object that will use them and such a class containing all these functions may not necessarily have any properties.

Treating them as a flat library file seems too simple, for lack of a better word.

What is the best practice for this?


Solution

  • Check out namespaces:

    http://www.php.net/manual/en/language.namespaces.rationale.php

    Wrapping them in a useless class is a workaround implementation of the concept of a namespace. This concept allows you to avoid collisions with other functions in large projects or plugin/module type deployments.

    EDIT

    Stuck with PHP 5.2?

    There's nothing wrong with using a separate file(s) to organize utility functions. Just be sure to document them with comments so you don't end up with bunchafunctions.php, a 20,000 file of procedural code of dubious purpose.

    There's also nothing wrong with prefixes. Using prefixes is another way to organize like-purpose functions, but be sure to avoid these "pseudo-namespaces" already reserved by the language. Specifically, "__" is reserved as a prefix by PHP [reference]. To be extra careful, you can also wrap your function declarations in function_exists checks, if you're concerned about conflicting functions from other libraries:

    if (!function_exists('myFunction')) {
        function myFunction() {
                //code
        }
    }
    

    You can also re-consider your object structure, maybe these utility functions would be more appropriate as methods in a base class that all the other objects can extend. Take a look at inheritance: http://www.php.net/manual/en/language.oop5.inheritance.php. The base class pattern is a common and very useful one:

    abstract class baseObject {
        protected function doSomething () {
            print 'foo bar';
        }
        public function getSomething () {
            return 'bar foo';
        }
    }
    
    class foo extends baseObject {
        public function bar () {
            $this->doSomething();
        }
    }
    
    $myObject = new foo();
    $myObject->bar();
    echo $myObject->getSomething();
    

    You can experiment with the above code here: http://codepad.org/neRtgkcQ