Laravel Transform 轉換器

xuyaoxiang發表於2020-02-27
abstract class Transform
{
    public function transformCollection(array $items,$transform='transform')
    {
        return array_map([$this, $transform], $items);
    }

    public abstract function transform($items);
}

繼承

class Demo extends Transform
{
    public function transform($items)
    {
        $mobel_user = new Users;
        $user = $mobel_user->find($items['uid']);
        return [
            'img'=>$user['img'],
            'nickname' => $user['nickname'],
            'demo_name' => $items['demo_name']
        ];
    }
}

例項化

$Demo = new Demo();
$items = $Demo->transformCollection($items);

轉換前資料

before=[
    ["id"=>1,"demo_name"=>"baba"],
    ["id"=>2,"demo_name"=>"mama"]
]

轉換後

after=[

["img"=>"baba_img","demo_name"=>"baba","nick_name"=>"baba_nick_name"],

["img"=>"mama_img","demo_name"=>"mama","nick_name"=>"mama_nick_name"]
]

當然user表和demo表是需要有關聯的。

這個轉換器的好用是不需要用foreach。
缺點是不能新增多個引數。

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章