How to transform a method call pattern found in multiple methods into a simpler OO mechanism?

69 views Asked by At

In my class I have a lot of functions that simply redirect code to a DAO class (a class that forms business objects from data from a database).

Is there a way to maybe create a single function that replaces all of the functions below?

public function getIdFromModel($model)
{
    return $this->motorDao->getIdFromModel($model);
}

public function getFrames($a, $b, $c)
{
    return $this->motorDao->getFrames($a, $b, $c);
}

public function getManufacturers()
{
    return $this->motorDao->getManufacturers();
}

What is the mechanism to do this and how is it used?

2

There are 2 answers

7
GolezTrol On BEST ANSWER

You could do that by implementing the magic method __call().

However, I would strongly recommend against it. Using magic methods is a lot slower, and it's harder for IDEs to display code insight information.

Also, you would still wind up with almost as much code, unless you pass everything on without even checking the method name. But if you do that, you have no validation whatsoever and anyone can just call any method of the DAO object. Question then is, why do you have this object inbetween in the first place?

0
hek2mgl On

You can use the magic method __call() for this:

public function __call($fname, $args) {
    call_user_func_array(array($this->motorDao, $fname), $args);
}

if you just want to redirect a defined set of functions to motorDao, use a whitelist:

public function __call($fname, $args) {
    if(in_array($fname, array(
        'functionA',
        'functionB',
        '...'
    ))) {
        call_user_func_array(array($this->motorDao, $fname), $args);
    } else {
        throw Exception(sprintf("%s has no method %s",
            get_class($this), $fname
        ));
    }
}