Open Source/plain-to-class/Usage/Anonymous array
Anonymous array
In case you need to convert an array of data into an array of class objects, you can implement this using the transformCollection method.
$data = [ ['id' => 1, 'name' => 'phone'], ['id' => 2, 'name' => 'bread'],];$products = ClassTransformer::transformCollection(ProductDTO::class, $data);As a result of this execution, you will get an array of ProductDTO objects:
array(2) { [0]=> object(ProductDTO) { ["id"]=> int(1) ["name"]=> string(5) "phone" } [1]=> object(ProductDTO) { ["id"]=> int(2) ["name"]=> string(5) "bread" }}You may also need a piecemeal transformation of the array. In this case, you can pass an array of classes, which can then be easily unpacked.
$userData = ['id' => 1, 'email' => 'test@test.com', 'balance' => 10012.23];$purchaseData = [ 'products' => [ ['id' => 1, 'name' => 'phone'], ['id' => 2, 'name' => 'bread'], ], 'user' => ['id' => 3, 'email' => 'fake@mail.com', 'balance' => 10012.23],];
$result = ClassTransformer::transformMultiple([UserDTO::class, PurchaseDTO::class], [$userData, $purchaseData]);
[$user, $purchase] = $result;var_dump($user);var_dump($purchase);Result:
object(UserDTO) (3) { ["id"] => int(1) ["email"]=> string(13) "test@test.com" ["balance"]=> float(10012.23)}
object(PurchaseDTO) (2) { ["products"]=> array(2) { [0]=> object(ProductDTO)#349 (3) { ["id"]=> int(1) ["name"]=> string(5) "phone" } [1]=> object(ProductDTO)#348 (3) { ["id"]=> int(2) ["name"]=> string(5) "bread" } } ["user"]=> object(UserDTO)#332 (3) { ["id"]=> int(3) ["email"]=> string(13) "fake@mail.com" ["balance"]=> float(10012.23) }}