I’d like to have a little php module. This module would have methods that are pure functions. So, this is just a collection of functions. All function get some arguments and return result depending only on input parameters.
I have some suggestions:
1. Static class
PHP hasn’t real static class, so I just make a class with all static methods:
class Some_Module
{
static public function sum($a, $b, $c)
{
return $a+$b+$c;
}
static public function method2($a, $b)
{
return $a-$b+5;
}
}
It’s very easy to use such modules:
$x = Some_module::sum(1,2,3);
But, I’ve heard (there are lots of topics on SO), that static is a bad practice.
2. Singleton
It’s not so easy to use:
// we should not to forget to get instance
$module_instance = new Some_module;
$x = $module_instance->sum(1,2,3);
Inconvenience is in that fact, that we should initialize this module now.
Also, there is a huge amount of topics on SO, where is explained why Singleton are not useful in PHP, so it’s a bad practice too.
What pattern to use for such a module?
I think this discussion will help in your decision Static methods: are they still bad considering PHP 5.3 late static binding?
Personally, it depends on the context. To store a bunch of misc. helper methods, more likely I’ll use it as a global and namespace it. In storing a limited amount of methods of a particular category that have no need to be instantiated, a static class might be a good option. Just be aware for unit testing purposes, many classes using static methods in the wrong context like
cool::methodis going to be hell.