我正在开发一个应用程序,我的数据来自 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/