1、背景:需要根据接口中文章的位置计算曝光,曝光由文章首图的日志统计处理,所以需要在文章首图的url中拼上当前文章的在此次接口中的位置以及当前页码
2、实现:当前文章在此次接口返回数据中的位置;
use Illuminate\Http\Resources\Json\Resource;
use App\Models\Traits\WithIndexTrait;
class SubjectToArrayResource extends Resource
{
use WithIndexTrait;
public $resource;
// default constructor to make
// anonymous class work
public function __construct($resource = null)
{
if ($resource) {
parent::__construct($resource);
}
}
public function toArray($request)
{
……
$this->index
……
}
public function with($request)
{
return [
'errcode' => 0,
'msg' => 'ok'
];
}
}
use App\Ship\Http\Json\ApiCollection;
trait WithIndexTrait
{
public $index;
public static function collection($resource)
{
return new class($resource, get_called_class()) extends ApiCollection
{
/**
* @var string
*/
public $collects;
/**
* Create a new anonymous resource collection.
*
* @param mixed $resource
* @param string $collects
*/
public function __construct($resource, $collects)
{
$this->collects = $collects;
parent::__construct($resource);
}
public function toArray($request)
{
return $this->collection
->map(function ($item, $key) use ($request) {
// 这个item指的是resource,不是model
$item->index = $key;
return $item->toArray($request);
})
->all();
}
};
}
}
网友评论