Home » Php » php – Best practice of Receiving bulk of data [laravel Restfult API]

php – Best practice of Receiving bulk of data [laravel Restfult API]

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a case of receiving bulk of data to handle it in APIs

what’s the best practice of receiving it

First approach => create multiple array each hold the data of each field

$names = ['SAM','John','Vardy'];

$ages = ['19','20','22'];

or
Second approach => create one array each index has it own object

$data = [
   {
     'name':'SAM',
     'age':'19'
   },
   {
     'name':'John',
     'age':'20'
   },
   {
     'name':'Vardy',
     'age':'22'
   },
];

what’s the best one of them ???

How to&Answers:

“Better” is a subjective term and on this site we deal with objective criteria. So, first, let’s define what “better” is in this case:

  • reusable
  • easy-to-maintain
  • understandable
  • reliable

Now, if you create many arrays with n elements each and the nth item of all will be interrelated, then you will always have to deal with some specific arrays, so this will not really be reusable. You can write some functions which ease some of the burden, but this does not change the fact that you will always have some specific columns to work with. If you have an array where each element represents a set of field-name field-value pairs, then as an idea this is reusable. You will just need to keep track of the column names and values, rather than creating an array of each column name.

The first approach is difficult to maintain, because whenever you need new fields, or field name changes, or removing some fields, then you will have to re-read entire code chunks. In the second approach you will just handle some fields.

The first is difficult to understand. An index is a number and tells you nothing and in order to understand an entity you will have to glue together nth elements of all arrays of an entity, something which comes as a free feature with the second approach.

The first approach is very unreliable. If an item is removed from an array, but not from the other, due to a bug, then your code will have the impression that some items are interrelated with the wrong pairs.

So, let’s have an array with field-name field-value pairs, you can implement some helper functions as well, in order to validate, add, remove or update items.

Answer:

This really depends on your needs, but for me, the second approach seems more consistent.