首页 文章

Laravel - 第三方API的模型?

提问于
浏览
1

我正在开发一个使用Laravel后端的iphone应用程序 . 在某些时候,将有Goole Places集成(或类似的服务) .

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

2 回答

  • 1

    我就是这样做的 .

    所有模型都从Eloquent ORM model class扩展,这意味着可以覆盖扩展类中的finders / getters / setter等 .

    您的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将用户与数据透视表中的地点相关联 .

  • 0

    我认为为第三方制作模型并不重要,因为它不是雄辩的服务和使用API的角色 . 否则我建议你提供服务:

    • 创建文件夹app / Service

    • 使用良好的命名空间创建一个类

    • 创建自己的功能 . 您可以创建配置文件并将其与Env变量一起使用来存储凭据

    • 最后在控制器中调用您的服务,然后在函数输入中声明它,laravel将自动解析它 .

    public function test(MyService $service)

相关问题