DEV Community

Ryan P
Ryan P

Posted on • Updated on

CSV Reader - Links

In my last two posts I covered the basics of my CSV Reader and the Filter and Map functionality. In this post, I wanted to cover the Link functionality. Links are similar to Map. The main difference is that Maps return a formatted string. Links return whatever you’d like to return from the callback method. A good example is Address data. You have a CSV file that has customer data that includes an address. Let’s say you want to isolate that address into it’s own Address object within the Customer object.

First you create the Address object

class Address
{
    

    public static function fromCSV(stdClass $data): Address
    {
        $me = new static();

        // you'll need to do validation on each field

        $me->address = $data->Address;
        $me->city = $data->City;
        $me->state = $data->State;
        $me->zip = $data->Zip;
        $me->country = $data->Country;

        return $me;
    }
}
Enter fullscreen mode Exit fullscreen mode

Then you need to create the Link and add it to the Reader.

$link = new Link(
    'objAddress',  // Field to call that will trigger this link
    [
        'Address', 'City', 'State', 'Zip', 'Country'
    ], // The fields as they appear in the CSV after removing invalid characters
    [
        Address::class, 'fromCSV'
    ], // The *optional* callable method to pass the data to
);
$reader->addLink($link);
Enter fullscreen mode Exit fullscreen mode

Then when you call the reader and reference the objAddress property it will call the method Address::fromCSV and it will pass in a stdClass object with each of the fields as a public property. The callback parameter is optional and if you omit it, the return will just be that stdClass object. This can be a great option as well.

Top comments (0)