【问题标题】:Laravel - A Model for a 3rd Party API?Laravel - 第 3 方 API 的模型?
【发布时间】:2015-08-08 14:32:14
【问题描述】:

我正在开发一个使用 Laravel 后端作为 API 的 iphone 应用程序。在某个时候,会有Google Places 集成(或类似服务)。

在我的应用程序中,我需要存储用户和地点之间的关系,这是多对多的。但是,由于“地点”不是由 Eloquent 模型(而是由 Google 的 API)表示的,我该如何创建这种关系?我需要为 Google Places API 创建一个包装器吗?

【问题讨论】:

    标签: laravel orm eloquent many-to-many


    【解决方案1】:

    我会这样做。

    您的所有模型都从基础 Eloquent ORM model class 扩展而来,这意味着可以覆盖扩展类中的查找器/获取器/设置器等。

    您的 Google Place 模型是一种特殊情况,它不依赖于数据库,而是依赖于 Google Places API。

    因此,您需要覆盖 Google Places 模型的基本 Eloquent 模型方法。

    例如:

    class GooglePlace extends Eloquent{
        /**
         * Find a model by its primary key or return new static.
         *
         * @param  mixed  $id
         * @param  array  $columns
         * @return \Illuminate\Support\Collection|static
         */
        public static function findOrNew($id, $columns = ['*'])
        {
           # we do not need Eloquent's database based implementation
           # api code to get Google Place using $id 
           # perhaps use $columns to get only specific fields about the place
           # from the API?
        }
    }
    

    然后,您只需使用 Google 地点 ID 将用户与数据透视表中的地点相关联。

    【讨论】:

      【解决方案2】:

      提供 API 和 Eloquent 模型透明度之间的复杂实现。我建议您使用https://github.com/CristalTeam/php-api-wrapper

      cristal/php-api-wrapper,您可以为您的 API 创建模型,并且您有一个专门适用于 API 请求的查询构建器。您可以使用高级 Laravel 功能,例如路由绑定以及 Eloquent 模型与此包的模型之间的关系。

      【讨论】:

        【解决方案3】:

        我认为为第 3 方创建模型无关紧要,因为服务和使用 API 不是 eloquent 的角色。 否则我建议您提供服务:

        • 创建文件夹 app/Service
        • 在内部创建一个具有良好命名空间的类
        • 创建您自己的函数。您可以创建一个配置文件并将其与 Env 变量一起使用来存储凭据
        • 最后在你的控制器中调用你的服务,然后在函数的输入中声明它,laravel 会自动解析它。

        public function test(MyService $service)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-07
          • 1970-01-01
          • 2021-10-17
          • 2023-02-16
          • 2018-12-07
          • 1970-01-01
          相关资源
          最近更新 更多