php - 来自外部源的 Laravel Eloquent 无表数据

标签 php laravel web-services eloquent relationship

我正在开发一个应用程序,我的数据来自 JSON 格式的外部服务器。

我想设置每个模型之间的关系,但不使用数据库表。

这可能吗?

类似的东西:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'https://.../server/flights.json';
}

最佳答案

您可以创建一个服务类来处理请求并返回类实例:

namespace App\Services;

class FlightService
{
    /**
    * @var FlightFactory
    */
    private $flightFactory;

    public function __construct(FlightFactory $flightFactory)
    {
        $this->flightFactory = $flightFactory;
    }

    public function getAllFlights()
    {
        $flightsJson = $this->getFromExternalCurl();
        return $this->flightFactory->buildFlightList($flightsJson);
    }

    private function getFromExternalCurl()
    {
        return Curl::to('http://www.foo.com/flights.json')
        ->withData( array( 'foz' => 'baz' ) )
        ->asJson()
        ->get();
    }

}

基本上,服务会进行外部 API 调用,并将响应传递给创建实例的工厂。

请注意,您只需要在构造中添加工厂并且它已绑定(bind),因为 laravel 使用 https://laravel.com/docs/5.4/container

namespace App\Factories;

class FlightFactory
{
    public function buildFlightList($flightJsonList)
    {
        $flightCollection = collect();
        foreach($flightJsonList as $flightJson) {
            $flightCollection->push($this->buildFlight($flightJson));
        }
        return $flightCollection;
    }

    public function buildFlight($flightJson)
    {
        $flight = new Flight();
        // add properties
        return $flight;
    }

}

工厂会返回一个Collection这非常有用,因为它包含有用的方法,或者您可以返回一个数组。

在这个例子中,我使用了一个 curl 库 https://github.com/ixudra/curl但可以用原生 php 或其他库替换。

然后您可以通过在您的 Controller 中注入(inject) FlightService 来使用。

P.S:代码未经测试,但代表了一种可能的方法

关于php - 来自外部源的 Laravel Eloquent 无表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47772103/

相关文章:

mysql - 具有两级关系的流明排序

java - Android 使用 WebService,异常 HttpTransportSE.call()

php - 如何检测按下了哪个提交按钮?

PHP foreach SplPriorityQueue - 找不到元素

php - Braintree dropin UI : validate billing address custom fields before form submit

php - Laravel Eloquent ORM中如何获取插入的多行数据

php - 在 Laravel 5.3 中覆盖 Auth 忘记密码

web-services - 在 Scala 中模拟外部 Web 服务的最轻量级 Web 服务框架

java - 如何为 Android 应用程序托管 Java RESTful Web 服务

php - 如何判断mysql中哪些列已设置为CASCADE