PHP Fractals(变形金刚)输出一些奇怪的json

时间:2016-06-17 15:41:59

标签: php json

所以我不知道这是不是常态,但这个json看起来并不容易使用,特别是对于前端开发人员。

所以使用these docs我为博客上的帖子做了默认包含,变换器是:

<?php

namespace App\Etis\Domain\Transformers\Blog;

use League\Fractal\TransformerAbstract;
use App\Etis\Domain\Entities\BlogsEntity;
use Carbon\Carbon;
use App\Etis\Domain\Transformers\Blog\Posts\PostsTransformer;

class BlogsTransformer extends TransformerAbstract {

    protected $defaultIncludes = [
        'posts'
    ];

    public function transform(BlogsEntity $blog) {

        return [
            'id'                => $blog->id,
            'belongs_to_user'   => $blog->user_id,
            'title'             => $blog->title,
            'created_at'        => $blog->created_at->format(Carbon::ISO8601),
            'updated_at'        => $blog->updated_at->format(Carbon::ISO8601)
        ];
    }

    public function includePosts(BlogsEntity $blog) {
        $posts = $blog->posts;

        return $this->collection($posts, new PostsTransformer);
    }
}

上面是博客变换器,我们可以看到包括帖子,所以让我们看看变换器:

<?php

namespace App\Etis\Domain\Transformers\Blog\Posts;

use League\Fractal\TransformerAbstract;
use App\Etis\Domain\Entities\PostsEntity;
use Carbon\Carbon;

class PostsTransformer extends TransformerAbstract {

    public function transform(PostsEntity $post) {
        return [
            'id'          => $post->id,
            'title'       => $post->title,
            'content'     => $post->content,
            'blog_id'     => $post->blog_id,
            'published'   => $post->published,
            'slug'        => $post->slug,
            'saved'       => $post->saved,
            'created_at'  => $post->created_at->format(Carbon::ISO8601),
            'updated_at'  => $post->updated_at->format(Carbon::ISO8601)
        ];
    }
}

超级简单,没什么复杂的。

{  
   data:[  
      {  
         type:"blogs",
         id:"2",
         attributes:{  
            belongs_to_user:2,
            title:"Everymans Thoughts",
            created_at:"2016-04-28T16:14:48+0000",
            updated_at:"2016-04-28T16:14:48+0000"
         },
         relationships:{  
            posts:{  
               data:[  
                  {  
                     type:null,
                     id:"2"
                  },
                  {  
                     type:null,
                     id:"3"
                  }
               ]
            }
         }
      },
      {  
         type:"blogs",
         id:"1",
         attributes:{  
            belongs_to_user:1,
            title:"GNI2BOWLHy",
            created_at:"2016-04-22T19:56:23+0000",
            updated_at:"2016-04-22T19:56:23+0000"
         },
         relationships:{  
            posts:{  
               data:[  
                  {  
                     type:null,
                     id:"1"
                  }
               ]
            }
         }
      }
   ],
   included:[  
      {  
         type:null,
         id:"2",
         attributes:{  
            title:"Sample Blog",
            content:"<p><img src="            http://lorempixel.com/900/400/" alt="Image" /></p> <p>Lorem markdownum Hymenaee. <em>Triste</em> tamen? Sed herbas opibusque ratem placebant timor Trachinia libera verba opem teste aquaticus ne est paulum ipse Aesonides?</p> <p>Lorem markdownum Hymenaee. <em>Triste</em> tamen? Sed herbas opibusque ratem placebant timor Trachinia libera verba opem teste aquaticus ne est paulum ipse Aesonides?</p> <p>Lorem markdownum Hymenaee. <em>Triste</em> tamen? Sed herbas opibusque ratem placebant timor Trachinia libera verba opem teste aquaticus ne est paulum ipse Aesonides? if (operation_bitrate_cron.gpsOsEmulation(kde_terahertz_qwerty,
            gigabyte( mask) + surfaceKeywords))            {  
               partition_whois += 2 + -2;
            }            memory *= portalLink; hdmi_tween = user.signature(mcaBooleanBatch * 54,
            header(driveDatabase),
            ip_latency);</p> <h2>Prope eripe consorte natis virgo appellant venisset</h2> <p>Gente cum audito nymphae <a href="http://hipstermerkel.tumblr.com/">levati veri ictibus</a>,
            aut arida,
            quantumque. Modo insistit <strong>quidem</strong>:satis parvos edaci totiens spectare,
            alto huic suis facitis nondum. Sorores <a href="http://www.thesecretofinvisibility.com/">oblita</a>,
            in ait pascas,
            tantum iam; speciem,
            labefactum. Postquam <strong>ager</strong> Talibus turba non uberrima,
            pulchro et quibus sententia munitos dum,
            et aquarum dubiae,
            pars. Terga vellet de Emathion Phlegyis Circes peremptam siccat,
            me suis Prochytenque.</p> <h2>A nostra</h2> <p>Paternos nequeunt,
            rapta,
            velles; fugisse his tergo plurima! Veni cognita cavernis et tergo interrumpente terra; nec ortus videtur cumque nunc! Dubitanti frater nunc moras tuque,
            est litore Plura. Haec color Ceres nitidis oculus,
            cum squamae,
            crede australem in abiere,
            te plebemque lentum!</p> <h2>Ab haec condi et suum memorabile nequiquam</h2> <p>Vulneribus docuique ridentem monstravit et <a href="http://gifctrl.com/">intacta vomit terroris</a> pia ille festumque iterque nunc,
            quamvis. Subito quid. Ad pariente mihi facto hortatibus nisi tamen pulsat dolor ac se,
            ille in orant quodcumque guttur,
            rite.</p> <blockquote> <p>Vultus Aiaci his picto,
            comitique huic,
            ferro:est certi,
            sententia commissas mater. Superi tabuerint terras intravit inertes conorque aurum reus mentas caelo ut et sintque:            <em>feruntur usus</em>. <a href="http://zombo.com/">Illa avsis noxque</a>,
            sua Bacchumque comminus positus. Cur igne paulatim?</p> </blockquote> <p>Non gauderet,
            vellere,
            auro halitus,
            fortuna non Picus me alios Cerberei potentes. Aquis praelatus soceri densa!</p> ",
            blog_id:2,
            published:true,
            slug:"sample-blog",
            saved:false,
            created_at:"2016-04-28T16:16:52+0000",
            updated_at:"2016-04-30T18:25:49+0000"
         }
      },
      {  
         type:null,
         id:"3",
         attributes:{  
            title:"asdasdasda",
            content:"<p>asdasdsadsa</p> ",
            blog_id:2,
            published:false,
            slug:"asdasdasda",
            saved:true,
            created_at:"2016-05-14T16:53:12+0000",
            updated_at:"2016-05-14T16:53:12+0000"
         }
      },
      {  
         type:null,
         id:"1",
         attributes:{  
            title:"yTxxDi0EwD",
            content:"YQzrVXMB5bXepspPNp0RLaCoqXYrWPgEvcZxcISrGcFBPFxic8KsdRYpvMLPlZenoJIlI2fpSwxbeTMtWDHZW8Z5fnUBBn6lTiVz",
            blog_id:1,
            published:true,
            slug:"ytxxdi0ewd",
            saved:false,
            created_at:"2016-04-22T19:56:23+0000",
            updated_at:"2016-04-22T19:56:23+0000"
         }
      }
   ],
   meta:{  
      pagination:{  
         total:2,
         count:2,
         per_page:15,
         current_page:1,
         total_pages:1,
         links:[  

         ]
      }
   }
}

如何使用这些变换器来获取所说的JSON?

我有一个控制器方法:

public function getBlogs() {
    $manager = new Manager();
    $manager->setSerializer(new JsonApiSerializer());

    if (\Auth::check()) {
      $paginatedBlogs = BlogsEntity::orderBy('created_at', 'desc')->paginate();
      $blogs          = $paginatedBlogs->getCollection();

      $resource = new Collection($blogs, new BlogsTransformer(), 'blogs');
      $resource->setPaginator(new IlluminatePaginatorAdapter($paginatedBlogs));

      return $manager->createData($resource)->toArray();
    } else {
      return response()->json(['error_message' => 'You cannot access this route.']);
    }
}
  1. 那么为什么我会得到那些无法使用的丑陋的JSON呢?
  2. 为什么帖子没有嵌套在各自的下面 博客吗

1 个答案:

答案 0 :(得分:2)

$manager->setSerializer(new JsonApiSerializer());设置Fractal以输出符合JSON-API标准的JSON,它具有非常特殊的规范(http://jsonapi.org/)。如果您不希望它复杂(但标准化,对前端人员可能非常有用)输出use a different (like the default one) serializer