2014-05-03 73 views
0

如何在Laravel中實現外部包的接口?說,我想使用Mashape/Unirest API來獲取文本分析,但將來我想切換到其他API提供程序,並且不要在代碼中進行太多改動。Laravel Mashape/Unirest 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?爲他們製作特殊的文件夾,添加到作曲家?添加命名空間?

回答

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'); 
+0

安東尼:感謝您的快速反應。應該是$ this-> analyzer-> setConfig()?那個類分析器可能是一個控制器,對吧? –

+0

當然,編輯;) –