0

How do you implement interface for external package in Laravel? Say, I want to use Mashape/Unirest API to get analyse of text, but in future I would like to switch to other API provider and do not change to much in code.

interface AnalyzerInterface {

    public function analyze(); //or send()?

}

class UnirestAnalyzer implements AnalyzerInterface {

    function __constructor(Unirest unirest){
        //this->...
    }

    function analyze($text, $lang) { 
        Unirest::post(.. getConfig() )
    }

    //some private methods to process data
}

And where to put that files interfece and UnirestAnalyzer? Make special folder for them, add to composer? Add namespace?

Antonio Carlos Ribeiro
  • 86,191
  • 22
  • 213
  • 204

1 Answers1

1

This is how I would go to Interface and Implement something like this:

interface AnalyzerInterface {

    public function analyze();
    public function setConfig($name, $value);

}

class UnirestAnalyzer implements AnalyzerInterface {

    private $unirest;

    private $config = [];

    public function __construct(Unirest unirest)
    {
        $this->unirest = $unirest;
    }

    public function analyze($text, $lang) 
    { 
        $this->unirest->post($this->config['var']);
    }

    public function setConfig($name, $value)
    {
        $this->config[$name] = $value;
    }

    //some private methods to process data
}

class Analyser {

    private $analizer;

    public function __construct(AnalyzerInterface analyzer)
    {
        $this->analyzer = $analyzer;

        $this->analyzer->setConfig('var', Config::get('var'));
    }

    public function analyze()
    {
        return $this->analyzer->analyze();
    }

}

And you must bind it on Laravel:

App::bind('AnalyzerInterface', 'UnirestAnalyzer');
Antonio Carlos Ribeiro
  • 86,191
  • 22
  • 213
  • 204
  • Antonio: thanks for quick response. Should it be $this->analyzer->setConfig() ? That class Analyser could be a controller, right? – Leszek Pietrzak May 03 '14 at 13:11