请问 NotificationTransformer 中的 transform 方法中的 $notification 参数不声明类型也可以?
请问老师,教程中提到:
但实际上,去掉此参数类型也可以。
class NotificationTransformer extends TransformerAbstract
{
public function transform($notification)
{
return [
'id' => $notification->id,
'type' => $notification->type,
'data' => $notification->data,
'read_at' => $notification->read_at
? $notification->read_at->toDateTimeString() : null,
'created_at' => $notification->created_at->toDateTimeString(),
'updated_at' => $notification->updated_at->toDateTimeString(),
];
}
}
并不会出错:
我觉得原因可能是因为:$notifications = $this->user->notifications()->paginate(20);
这里的$notifications
中已经是通知类的集合\Illuminate\Notifications\DatabaseNotificationCollection
了,然后在最后遍历此集合时,就直接传入就好了。\League\Fractal\Scope::executeResourceTransformers
:
protected function executeResourceTransformers()
{
...
foreach ($data as $value) {
list($transformedData[], $includedData[]) = $this->fireTransformer($transformer, $value);
}
...
}
\League\Fractal\Scope::fireTransformer
$transformedData = $transformer->transform($data);
这里的$transformer
就是\App\Transformers\NotificationTransformer
,$data
就是一个\Illuminate\Notifications\DatabaseNotification
对象。
所以,transform中似乎不用声明参数的类型?谢谢
推荐文章: