json-api-php / json-api

Implementation of JSON API in PHP
https://json-api-php.github.io/
MIT License
183 stars 18 forks source link

Creating collections from array #88

Closed techi602 closed 5 years ago

techi602 commented 5 years ago

I must be missing something very obvious yet I still can not understand how am I suppose to work with dynamic collections created from array. Imagine common task like retrieving orders from database and return several records as resource objects. (Number of orders is dynamic). How am I supposed to create resource collection? I can not simply pass array of Resource objects into constructor. I am aware of immutable objects, but still why I can not simply create immutable instance like ResourceArray and pass array of ResourceObjects ? Should I write my own ResourceArray class which will extend ResourceCollection and allow me to pass the array directly in constructor?

even example here passes dynamic number of comments into constructor - not sure about this https://github.com/json-api-php/json-api/blob/master/examples/compound_doc.php

@OndraM

f3ath commented 5 years ago

Hi @techi602. Thank you for your interest. This library makes extensive use of variadic functions to improve type safety. You can use argument unpacking to pass a dynamic number of arguments.

$resources = getResources(); // array of ResourceObject
$collection = ResourceCollection(...$resources);

Let me know if this answers the question.

f3ath commented 5 years ago

but still why I can not simply create immutable instance like ResourceArray and pass array of ResourceObjects ?

You can. But in this case you will either need to check that the elements of the array are ResourceObjects (which is cumbersome) or to blindly trust the user input. The variadic/unpacking approach lets php do the type checking. While it can still blow up in the runtime due to the dynamic nature of the language, the modern IDEs make sense of these type hints and reduce the chance of errors by checking types in the development time.

techi602 commented 5 years ago

@f3ath thanks a lot! 👍 I was not aware of argument unpacking feature and "array type checking" I would suggest to add similar code to examples for other confused developers 😜

f3ath commented 5 years ago

@techi602 I would gladly accept a PR from you with such an example if you don't mind.