【问题标题】:Can I use transformers to transform data coming from API rather than from database?我可以使用转换器来转换来自 API 而不是来自数据库的数据吗?
【发布时间】:2017-12-10 00:57:30
【问题描述】:

我一直在使用 laravel 来构建我的 API。我使用转换器来转换模型对象中的数据。

现在我有一个来自 API 的响应而不是数据库作为数据源,我想将该数据转换回用户,但我无法这样做。

我的控制器

 public function rocByName(Request $request)
    {
        try {
            $this->roc_by_name_validator->with( $request->all() )->passesOrFail();
            $company_name = $request->input('company_name');
            $result = $this->my_service->getDetailsByName($company_name); //$result has the response object from the API which I want to transform and give it as a response.

             return $this->response->collection($result,new OnboardingTransformer()); //Tried using tranformer like this
        }
        catch (ValidatorException $e) {

            dd($e);

        }

    }

我的变压器

<?php

namespace Modules\Onboarding\Transformers;

use League\Fractal\TransformerAbstract;
use App\Entities\OnboardingEntity;  //I dont have an entity since the response is coming from an API!! What will give here?

/**
 * Class OnboardingTransformerTransformer
 * @package namespace App\Transformers;
 */
class OnboardingTransformer extends TransformerAbstract
{

    /**
     * Transform the \OnboardingTransformer entity
     * @param \OnboardingTransformer $model
     *
     * @return array
     */
    public function transform(OnboardingEntity $data_source) 
    {
        return [
            'company_name'         => $data_source->company_name,
        ];
    }
}

这里的 OnboardingEntity 是指理想情​​况下来自数据库的数据。在这里,我不是从数据库中获取数据,而是我的数据来自 API 源。我该怎么做。我在这里有点困惑。有人可以给出解决方案吗?

$result 有以下响应

[
    [
        {
            "companyID": "U72400MHTC293037",
            "companyName": "pay pvt LIMITED"
        },
        {
            "companyID": "U74900HR2016PT853",
            "companyName": "dddd PRIVATE LIMITED"
        }
    ]
]

【问题讨论】:

  • 我相信您不需要将其转换为收藏。您可以直接将数组传递给转换器。
  • @AdnanMumtaz 那也很好。您可以在答案中添加示例代码吗?
  • $result = $this-&gt;my_service-&gt;getDetailsByName($company_name) 你是在接收$results中的集合还是数组
  • @AdnanMumtaz 我已经用 $result 中的示例响应更新了这个问题。请检查。它是一个数组
  • @companyName 公司名称怎么可以是整数?

标签: php laravel transformer dingo-api thephpleague-fractal


【解决方案1】:

$this-&gt;response-&gt;collection 旨在获取对象集合,而不是数组。然后所有这些对象都将进入转换器,即根据需要转换 OnboardingEntity 对象。因此,首先您应该将输入数组转换为对象集合。我上面的例子(你应该把它改成你自己的输入数组)

$data = json_decode('[
    [
        {
            "companyID": "U72400MHTC293037",
            "companyName": "pay pvt LIMITED"
        },
        {
            "companyID": "U74900HR2016PT853",
            "companyName": "dddd PRIVATE LIMITED"
        }
   ]
]');  

$data = collect( array_map( function($ob){
    return (new OnboardingEntity($ob));
}, $data[0]));

然后将这个 OnboardingEntity 对象的集合传递给$this-&gt;response-&gt;collection 方法,就像这里 $this-&gt;response-&gt;collection($data,new TestTransformer());

【讨论】:

  • 如果对象的字段从响应变为响应,我将如何创建实体 OnboardingEntity?我必须为每个响应创建模型吗?
  • @Ajeesh 这不是必需的,但我强烈建议您这样做。如果您不想为所有响应数组实体创建模型,则必须在转换方法中删除参数类型,否则它将收到 stdClass 对象,您将能够通过 -> 运算符访问属性。 $data=collect($data[0]);//convert to stdClass collection 和 transform 函数看起来像:public function transform($data_source) { return [ 'company_name' =&gt; $data_source-&gt;companyName, ]; } 无论您需要为所有类型的响应创建转换器,因为它们有差异字段
  • 这个答案不清楚..想知道为什么它被赞成..它对任何人都有效吗?
【解决方案2】:

您可能希望将通用数据结构发送到 Fractal,因为数据源不同。数组是最适合您的类型。

当您从 Eloquent(DB) 获取数据时请考虑这一点:

 $result = $yourModel->get(); // This will return you with a collection object.

在将此对象传递给分形之前将其转换为数组。

 $this->response->collection($result->toArray(),new OnboardingTransformer());

如果是first 或单个模型对象。在调用 toArray() 之前检查 null。

 $result = $yourModel->first();
 if($result){
      $result = $result->toArray(); 
 }
 // Fractal itself can handle null 

现在是第二种情况,数据来自 API 或文件等外部源。

 $result = $this->my_service->getDetailsByName($company_name);
 // Try converting your response object to array from within

您可以使用json_decode(&lt;Body of response&gt;, true) 执行此操作。然后将此数组传递给 Fractal。

为什么是数组?
因为数据源可以是从数据库到文件、从缓存到 API 的任何东西。格式可以是 JSON 或 XML。将所有这些转换为数组是 PHP 内置的。

【讨论】:

    猜你喜欢
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    相关资源
    最近更新 更多