如何在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
}那么,将该文件接口和UnirestAnalyzer放在哪里呢?为他们制作特殊的文件夹,添加到composer?添加命名空间?
发布于 2014-05-03 20:21:35
这就是我如何转到Interface并实现类似如下的东西:
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');https://stackoverflow.com/questions/23443964
复制相似问题