重复调用 -假设你需要你的应用程序与API对话,你正在使用guzzle或包装器或任何东西。我发现自己不得不在每个控制器函数中调用连接,例如:
class ExampleController extends Controller
{
public function one()
{
$client = new Client();
$response = $client->get('http://',
[ 'query' => [ 'secret' => env('SECRET')]]);
$json = json_decode($response->getBody());
$data = $json->object;
// do stuff
}
public function two()
{
$client = new Client();
$response = $client->get('http://',
[ 'query' => [ 'secret' => env('SECRET')]]);
$json = json_decode($response->getBody());
$data = $json->object;
// do stuff
}
}
我如何更好地处理这个?我是否使用服务提供商?如果是这样,我如何最好地实现这些调用?我应该创建另一个控制器并调用每个函数中的所有API连接,然后包括该控制器并根据需要调用每个函数吗?我应该把它放在__construct?
让我们试试依赖倒置原则
一开始这可能听起来有点难,我的代码可能有一些拼写错误或小错误,但试试这个
需要创建接口
namespace app'puttherightnamespace; // this deppends on you
interface ExempleRepositoryInterface
{
public function getquery(); // if you passinga variable -> public function getquery('variable1');
}
现在您必须创建repo
class ExempleRepository implements ExempleRepositoryInterface {
public function getquery() {
$client = new Client();
$response = $client->get('http://',
[ 'query' => [ 'secret' => env('SECRET')]]);
$json = json_decode($response->getBody());
return $json->object;
}
现在,最后一步是将接口绑定到服务提供者注册方法中的repo
public function register()
{
$this->app->bind('namespacehere'ExempleRepositoryInterface', 'namespacehere'ExempleRepository');
}
现在每次你需要控制器中的结果时你所要做的就是取出
class ExempleController extends Controller {
private $exemple;
public function __construct(ExempleRepositoryInterface $home) {
$this->exemple = $exemple;
}
public function test() {
$data = $this->exemple->getquery(); / you can pass a variable here if you want like this $this->exemple->getquery('variable');
// do stuff
}
这不是最简单的方法,但我想这是最好的方法