在PHP中使用Fractal over toArray()有什么好处

时间:2015-10-08 03:28:35

标签: php api oop

我偶然发现了PHP联盟Fractal,它表明目的是确保存储和输出(客户端)之间的输出格式。

我已经使用API​​超过一年了,我为我希望返回的大多数实体构建了toArray()函数。在Eloquent的帮助下,如果你已经用Eloquent模型附加了你的实体模型,你可以重载toArray()函数并从那里进行装饰。

示例:

public function toArray()
{
    $array = parent::toArray();
    $array['extra'] = true;
    ...
    return $array;
}

如果Apis应该快速轻巧,那么PHP League的Fractal在实现toArray()方面有什么优势,或者从存储库/管理器中获得格式($ data)函数?是因为OOP吗?若有,有人可以展示一个例子吗?

1 个答案:

答案 0 :(得分:0)

For me the advantages are:

  • consistent response format enforced by passing models through Fractal's resource objects
  • ability to rather easily change the response format throughout the application with a simple switch of a serialiser (e.g., from json-api to hal and possibly more). For json-api it does the boring stuff like splitting actual response data and root metadata. Also you can easily change response depending of Accept header, which might be harder with array (you'd need to restructure it and certainly you don't want that clutter in your controller).
  • automation of links generation e.g., for pagination

I think first two are not exclusive to Fractal, but would be a purpose of having any abstraction for response formatting.

What is unclear for me, is where does something like Fractal belong? I'm a big fan of the view that the model should be able to represent itself, like it does with __toString. But then again one might argue that it's more a concern of the presentation than the model. With using fractal's pagination, embedding support it get even less clear, because that (for me) strays a bit beyond the presentation itself.

Speed concern is of course valid, but you can optimise elsewhere, e.g. by caching whole response content on something like varnish or some laravel package that performs the similar role if you don't have the infrastructure (caveat being that it's not applicable to every use case, authorised or varied user-specific responses being case in point).

As for examples I can recommend two, beside the package docs:

Would love to see some writeup of how something like Fractal can fit into a bigger, structured project.