0

I have the following class, API, that 'receives' functions from other classes (just Pipelinesin this example), so API::getPipelines() returns Pipelines::getPipelines() and so on. The list of API functions will grow and this code will grow larger and larger was well, so I'm looking for a way to dyamically add these functions to the API class. For example: register_methods_from(array('Pipelines', 'Blah')). What is the best way to do this?

class API
{

/**
 * The current API instance
 */
private static $_instance = null;

[...]

/**
 * Define API funcs
 */
public static function getPipelines() {
    return Pipelines::getPipelines();
}
public static function getPipeline($id) {
    return Pipelines::getPipeline($id);
}

// etc...
1
  • 2
    Use __call for example and check if method exists in Pipeline class, after that invoke it or not. Commented Sep 27, 2014 at 11:15

1 Answer 1

2

You can use PHP's magic method __callStatic for this:

class API
{
    static function __callStatic($name, $arguments)
    {
        if ( ! method_exists('Pipelines', $name))
        {
            return null; // Or throw error
        }

        return call_user_func_array('Pipelines::' . $name, $arguments);
    }
}

You can even make Pipelines dynamic here.

Also you may want to use autoloading instead, which allows you to return an instance of Pipelines when something like $api = new API(); is used.

Hope it helps!


Sources:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.