2014-05-24 3 views
3

발표자 (like this one)가 decorator pattern을 구현했으며 기존 Laravel 모델에 필드와 로직을 추가하는 좋은 방법임을 최근에 발견했습니다. 오히려 JSON 응답을 반환하는 API의 장식 패턴을 구현하는 것이 어떻게JSON 응답을위한 Laravel 발표자

{{ $object->timeago }} 
{{ $object->created_at }} 

:

// Tack on a new readable timestamp field. 
public function timeago() 
{ 
    return $this->object->created_at->whenForHumans(); 
} 

// Wrap an existing field with some formatting logic 
public function created_at() 
{ 
    return $this->object->created_at->format('Y-m-d'); 
} 

그때 내보기에 이러한 발표자 필드를 사용할 수 있습니다 : 아래 내 질문에 대한 다음의 예를 가지고 블레이드보기보다? 내가 읽은 모든 Laravel/JSON 기사에서 객체는 변형/발표자 논리를 거치지 않고 즉시 반환됩니다. 예 :

// converting a model to JSON 
return User::find($id)->toJson(); 

// returning a model directly will be converted to JSON 
return User::all(); 

// return associated models 
return User::find($id)->load('comments')->get(); 

내 JSON 응답에 발표자 필드를 구현하려면 어떻게해야하나요? 데이터를 얻을 장식 된 응답을 반환하는

일부 기능 :

public function index() 
{ 
    $news = News::all(); 

    return $this->respond([ 
      'data' => $this->newsTransformer->transformCollection($news->toArray()) 
     ] 
    ); 
} 

위의 함수를 호출 할 것이다 당신이 언급 한 바와 같이

$object->timeago 
$object->created_at 

답변

2

는 사용자 : 모든 그래서 그런 짓을, JSON을 반환 Transformer :: transformCollection :

<?php namespace Blah\Transformers; 

abstract class Transformer { 

    public function transformCollection(array $items) 
    { 
     return array_map([$this, 'transform'], $items); 
    } 

    public abstract function transform($item); 
} 

차례로 NewsTransformer :: transform()을 호출합니다.

public function transform($news) 
{ 
    return [ 
     'title' => $news['title'], 
     'body' => $news['body'], 
     'active' => (boolean) $news['some_bool'], 
     'timeago' => // Human readable 
     'created_at' => // Y-m-d 
    ]; 
} 

그 결과이 경우, 당신이 필요로하는 형식으로 JSON 인 : 그런데

{ 
    data: { 
     title: "Some title", 
     body: "Some body...", 
     active: true, 
     timeago: "On Saturday, 1st of March", 
     created_at: "2014-03-01" 
    } 
} 

Laracasts이 API를 구축에 우수한 시리즈가 있습니다 - 도움이되기를 바랍니다! 당신은 사용자 정의를 반환하는 대신 모델`toJson`을 무시할 수

return Response::json($data, 200); 
+0

:

명확성을 위해

은 첫 번째 코드에 응답 기능은 상태 코드와 데이터, 및 헤더, 같은 랩 응답. 훨씬 더 깨끗합니다. –

+0

@SergiuParaschiv, [toArray' 함수]를 재정의해야한다는 것을 알았습니다 (https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Model.php#L2359). 왜냐하면 Laravel은 컬렉션을 반환 할 때 toJson 메서드를 호출하지 않기 때문입니다. 그러나 두 메서드 (Model :: toJson 및 Collection :: toJson)는 각 모델에 대해 toArray를 호출합니다. – rvignacio