首页 > 解决方案 > 将第三方包设置为自定义服务提供商

问题描述

我正在尝试将一种“存储库模式”应用于自定义服务。

我想做的是将这个库实际绑定到我的自定义服务提供程序以创建一个抽象层,并最终在将来将该库切换到另一个库。

我正在尝试将'providers''aliases'引用从config/app.php我的服务提供商移动,但出现Class 'GoogleMaps' not found错误。

我已经添加App\Providers\GeoServiceProvider::classconfig/app.phpproviders 数组中,这是我的相关代码:

GeoServiceProvider.php(我的定制服务提供商)

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class GeoServiceProvider extends ServiceProvider
{
    /**     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(\App\Interfaces\GeoInterface::class, \App\Services\GoogleGeoService::class);

        $this->app->alias(\GoogleMaps\Facade\GoogleMapsFacade::class, 'GoogleMaps');
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {

    }
}

GeoInterface.php定义标准方法的接口

<?php
namespace App\Interfaces;


interface GeoInterface
{
    public function geoCode();
}

GoogleGeoService.php(实际的库实现)

<?php

namespace App\Services;

use App\Interfaces\GeoInterface;


class GoogleGeoService implements GeoInterface
{
    public function geoCode()
    {
        $response = \GoogleMaps::load( 'geocoding' ) <--- HERE IS WHERE I GET THE ERROR
            ->setParamByKey( 'latlng', "45.41760620,11.90208370")
            ->setEndpoint( 'json' )
            ->get();
        $response = json_decode($response, true);
        return $response;
    }
}

TestController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Interfaces\GeoInterface;

class TestController extends Controller
{

    protected $geoService;

    public function __construct(GeoInterface $geoService) {
        $this->geoService = $geoService;
    }

    public function index() {
        return $this->geoService->geoCode();
    }
}

谢谢你,亚历克斯

标签: laravel

解决方案


推荐阅读