📜  导入外观 URL laravel - PHP (1)

📅  最后修改于: 2023-12-03 14:53:41.582000             🧑  作者: Mango

导入外观 URL Laravel - PHP

在 Laravel 中,外观是一种设计模式,提供了简单的访问应用程序服务的方式,而不需要暴露其基础实现。外观还可以用于调用不受限制的静态方法。

有时,我们需要扩展外观的功能。为了实现这一点,我们可以通过实现 Illuminate\Contracts\Support\DeferrableProvider 接口来将服务别名注册到服务容器中。

当我们需要使用外观时,只需指定外观的类名即可。然后,Laravel 将自动创建外观实例并调用其方法。

在本教程中,我们将介绍如何导入外观 URL,并使用它发送 HTTP 请求。

步骤1:安装 Guzzle HTTP 客户端

我们将使用 Guzzle HTTP 客户端来发送 HTTP 请求。在要使用 Guzzle 时,请先安装它。您可以使用 Composer 进行安装:

composer require guzzlehttp/guzzle

Markdown 代码片段:

composer require guzzlehttp/guzzle
步骤2:导入 URL 外观

现在,我们将创建一个名为 UrlFacade 的类,该类将充当 URL 外观。此类将封装 Guzzle HTTP 客户端,并使其易于使用。

namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class UrlFacade extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'url';
    }
}

Markdown 代码片段:

namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class UrlFacade extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'url';
    }
}

如您所见,UrlFacade 继承自 Illuminate\Support\Facades\Facade 类。getFacadeAccessor 方法指定了用于解析外观的服务的名称。

步骤3:注册 Guzzle HTTP 客户端

现在,我们需要将 Guzzle HTTP 客户端注册到服务容器中。我们将在 AppServiceProvider 类的 register 方法中执行此操作。

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use GuzzleHttp\Client as Guzzle;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton('url', function () {
            return new Guzzle;
        });
    }
}

Markdown 代码片段:

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use GuzzleHttp\Client as Guzzle;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton('url', function () {
            return new Guzzle;
        });
    }
}

在此示例中,我们使用 GuzzleHttp\Client 类创建了类名为 url 的单例实例。

步骤4:发送 HTTP 请求

现在,我们可以使用我们的 UrlFacade 类发送 HTTP 请求。

use App\Facades\UrlFacade;

$response = UrlFacade::get('https://jsonplaceholder.typicode.com/users');

dd($response->getBody()->getContents());

Markdown 代码片段:

use App\Facades\UrlFacade;

$response = UrlFacade::get('https://jsonplaceholder.typicode.com/users');

dd($response->getBody()->getContents());

如您所见,我们使用 UrlFacade 类发送 GET 请求,并将 JSON 响应输出到 dd 函数。

我们现在已成功导入了 URL 外观,您可以使用它轻松发送 HTTP 请求。