请问 NotificationTransformer 中的 transform 方法中的 $notification 参数不声明类型也可以?

请问老师,教程中提到:
file

但实际上,去掉此参数类型也可以。

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(),
        ];
    }
}

并不会出错:
file

我觉得原因可能是因为:$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中似乎不用声明参数的类型?谢谢

日拱一卒
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
liyu001989
最佳答案

@hustnzj 你把 User::paginate() 传进去试试,要传一个 paginator。报错的性质不一样

5年前 评论
讨论数量: 4
liyu001989

这是只是个参数限定啊,我这个 transformer 只用于转换某个对象,传个 User 进来就报错了,这样不是更安全?

5年前 评论

@liyu001989 明白,不过不写参数的话,传一个user进来也会报同样的错。。。

file

file

5年前 评论
liyu001989

@hustnzj 你把 User::paginate() 传进去试试,要传一个 paginator。报错的性质不一样

5年前 评论

@liyu001989 明白了,如果没限制参数类型,那么传进去错误的对象也不会报错,实际上这里应该是需要报错的。谢谢老师。

file

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!