听起来你正在使用Guzzle来连接到第三方API,并且你想要在控制器中实例化Guzzle并调用Guzzle方法 .
一种解决方案是编写一个处理API调用的库类 . 例如
class MyAPILibrary
{
public function readImportantData($parameters)
{
// use Guzzle to connect to the API, pass the parameters, and read
// the important data
return $importantData;
}
}
然后,在您的控制器中,只要您需要该数据:
public function getIndex()
{
// I need that important data!
$d = MyAPILibrary::readImportantData($myParameters);
// and use the data...
return View::make("template")->with("important", $d);
}
请注意,我假设您为库设置了服务提供程序和外观,因此您可以进行类似 MyAPILibrary::readImportantData($myParameters) 的方法调用 . 有关该教程的详细教程,请参阅this page .
这个设置的好处是你现在可以测试你的API库,而不需要触摸你的控制器 . 再加上您的控制器变得更轻 - 通常是一两行 . 例如,上面的示例可以重写:
public function getIndex()
{
return View::make("template")
->with("important", MyAPILibrary::readImportantData($myParameters));
}
瞧!一线控制器方法!