How to create your own Faker Provider, vCards is gonna be! :)

Basically I need a way to generate vCards fake's ones to seed my database and test my API, we are using under the hood the new Laravel Lumen micro framework, however we are not gonna talk about Lumen in here just about Faker and explain how you can create your own Provider.

Let's get started

Is good have in mind the following:

And since Faker starts with the last provider, you can easily override existing formatters: just add a provider containing methods named after the formatters you want to override.

You can find the code that does all this on our repo cloudmanaged/vcard-faker-provider

However all the code you are gonna find there is basically the following:

<?php namespace Faker\Provider;  
class VCard extends \Faker\Provider\Base  
    public function vcard()
        $raw = 'BEGIN:VCARD' . "\n" .
            'N:' . $this->generator->lastName. ';' . $this->generator->firstName . ';;' . $this->generator->title . ';' ."\n" .
            'ADR;DOM;PARCEL;HOME:;;' . $this->generator->streetAddress . ';' . $this->generator->city .';' . $this->generator->state. ';' . $this->generator->postcode . ';' . "\n" .
            'EMAIL;INTERNET:' . $this->generator->email . "\n" .
            'ORG:' . $this->generator->company . "\n" .
            'TITLE:' . $this->generator->bs . "\n" .
        return $this->generator->parse($raw);

 Let's use it

To use it we just need to add it first to our composer file:

  • First add the repository
 "repositories": [
  • And then add the requirement
composer require cloudmanaged/vcard-faker-provider  

Once we got it add the dependecies to our project we can use it like:

$faker = \Faker\Factory::create();
$faker->addProvider(new \Faker\Provider\en_US\Person($faker));
$faker->addProvider(new \Faker\Provider\en_US\Address($faker));
$faker->addProvider(new \Faker\Provider\en_US\PhoneNumber($faker));
$faker->addProvider(new \Faker\Provider\en_US\Company($faker));
$faker->addProvider(new \Faker\Provider\Internet($faker));
$faker->addProvider(new Faker\Provider\VCard($faker));

And that will return a new vCard each time

  • This is the library we are using and you can see here all the actuals Providers that came out of the box with that library.

  • Here you'll find a good tutorial from Sitepoint talking and introducing us to the Faker library.