Syntactic sugar in PHP with static functions
Posted
by
Anna
on Programmers
See other posts from Programmers
or by Anna
Published on 2012-10-09T12:16:35Z
Indexed on
2012/10/09
15:54 UTC
Read the original article
Hit count: 381
The dilemma I'm facing is: should I use static classes for the components of an application just to get nicer looking API?
Example - the "normal" way:
// example component
class Cache{
abstract function get($k);
abstract function set($k, $v);
}
class APCCache extends Cache{
...
}
class application{
function __construct()
$this->cache = new APCCache();
}
function whatever(){
$this->cache->add('blabla');
print $this->cache->get('blablabla');
}
}
Notice how ugly is this->cache->...
. But it gets waay uglier when you try to make the application extensible trough plugins, because then you have to pass the application instance to its plugins, and you get $this->application->cache->...
With static functions:
interface CacheAdapter{
abstract function get($k);
abstract function set($k, $v);
}
class Cache{
public static
$ad;
public function setAdapter(CacheAdapter $a){
static::$ad = $ad;
}
public static function get($k){
return static::$ad->get($k);
}
...
}
class APCCache implements CacheAdapter{
...
}
class application{
function __construct(){
cache::setAdapter(new APCCache);
}
function whatever()
cache::add('blabla', 5);
print cache::get('blabla');
}
}
Here it looks nicer because you just call cache::get()
everywhere. The disadvantage is that I loose the possibility to extend this class easily. But I've added a setAdapter method to make the class extensible to some point. I'm relying on the fact that I won't need to rewrite to replace the cache wrapper, ever, and that I won't need to run multiple application instances simultaneously (it's basically a site - and nobody works with two sites at the same time)
So, am doing it wrong?
© Programmers or respective owner