0

你如何在 Laravel 中实现外部包的接口?比如说,我想使用 Mashape/Unirest API 来分析文本,但将来我想切换到其他 API 提供程序,并且不会对代码进行太多更改。

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
}

以及在哪里放置这些文件 interfece 和 UnirestAnalyzer?为他们制作特殊文件夹,添加到作曲家?添加命名空间?

4

1 回答 1

1

这就是我如何去接口和实现这样的东西:

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();
    }

}

你必须在 Laravel 上绑定它:

App::bind('AnalyzerInterface', 'UnirestAnalyzer');
于 2014-05-03T12:21:34.650 回答