如何在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?为他们制作特殊文件夹,添加到作曲家?添加命名空间?
答案 0 :(得分: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');