Laravel 以服务提供者的方式使用第三方扩展包

编辑于 2022-12-31 11:08:51 阅读 742

下面以使用腾讯地图webservices的php封装为例

先安装

composer require chudaozhe/tencent-map-api -vvv

先看下以普通方式使用

$key = '';//腾讯地图key
$secret_key = '';//SecretKey (SK):在腾讯位置服务控制台 > Key配置中,勾选WebServiceAPI的 SN校验时自动生成的随机字串,用于计算签名(sig)
$app = new \DeathSatan\TencentMapApi\Application($key, $secret_key);

//地址转经纬度
$data=$app->api()->addressResolution('北京市');
var_dump($data);

再看下以服务提供者的方式使用

第一步

通过通过artisan命令创建TencentMapServiceProvider

或者手动创建也行

root@php-fpm:/var/www/laravel-demo# php artisan make:provider TencentMapServiceProvider

执行成功会生成一个文件:app/Providers/TencentMapServiceProvider.php

第二步

添加一个配置文件

vi config/tencentmap.php
<?php
declare(strict_types=1);
return [
    //开发密钥(Key)
    'key'            => env('TENCENT_MAP_KEY', 'aaaa...'),
    //SecretKey (SK)
    'secret_key'     => env('TENCENT_MAP_SECRET_KEY', 'bbbb...'),

];

第三步

接着修改app/Providers/TencentMapServiceProvider.php文件中的register方法

    public function register(): void
    {
        $this->app->singleton(Application::class, function ($app) {
            return new Application(config('tencentmap.key'), config('tencentmap.secret_key'));
        });

        $this->app->alias(Application::class, 'tencentmap');
    }

第四步

注册服务

vi config/app.php

    'providers'       => [
...
        App\Providers\TencentMapServiceProvider::class,

    ],

第五步

使用,这里以控制器为例

use DeathSatan\TencentMapApi\Application;
class Other extends Controller{
    protected Application $svc;

    public function __construct()
    {
        $this->svc = app('tencentmap');
    }

    public function test()
    {
        try {
            $data = $this->svc->api()->addressResolution('北京市')->toArray();
            var_dump($data);
        } catch (GuzzleException $e) {
            throw new Exception($e->getMessage(), 500);
        }
    }
}

参考

https://segmentfault.com/a/1190000016824040

https://learnku.com/docs/laravel/9.x/providers/12207

广而告之,我的新作品《语音助手》上架Google Play了,欢迎下载体验