PHP help while migrating Connect v1 APIs to Square APIs

I am finally getting around to migrating my code using Connect v1 API to the Square APIs. I was able to get the quickstart example working and have modified my first piece of production code. I have a question about how to best migrate my code. I confess that I’m not a seasoned PHP programmer but I have been successful in creating several pieces of code we use regularly in our production environment at our cafe.
With the move to Square API I understand that there are setters and getters for all parameters and results. In the quickstart I find the following:

    foreach ($result->getLocations() as $location) {
        printf(
            "%s: %s, %s, %s<p/>", 
            $location->getId(),
            $location->getName(),
            $location->getAddress()->getAddressLine1(),
            $location->getAddress()->getLocality()
        );

All of my current Connect API code makes use of the returned arrays and I would like to retain as much of this as possible. If find that I can replace the above code with this:

    foreach ($result->getLocations() as $location) {
        $array = json_decode(json_encode($location), true);
        echo '<br>'.$array['id'].': '.$array['name'].', '.$array['address']['address_line_1'].', '.$array['address']['locality'].'<br>';

Can someone provide me some guidance on best practices for coding my PHP to extract the data being returned by the Square API calls.
Thank You!

I know it’s a pain, but I suspect you may need to at least use the setter methods as the values are read only and trying to assign to them will produce runtime errors. Even if that’s not relevant (eg for new objects maybe?), in my mind it’s best practice to use the getters and setters in most contexts.

From a maintenance point of view, your code is then consistent with what (I hope) is in the quickstart and other Square examples, so is more maintainable over time. I’d say directly accessing underlying values is the sort of thing that could break, even if it’s just the sub-components of each location.

1 Like