Getting Started

Custom Extension

Custom extension for Xefi Faker PHP

You can easily create a customized Faker extension. To do so, simply define a PHP class that extends the Xefi\Faker\Extensions\Extension class, and define the functions you wish to make available.

Example

use Xefi\Faker\Extensions\Extension;

class CustomEmailExtension extends Extension
{
    public function generateRandomEmail(string $domainName): mixed
    {
        $randomBytes = $this->randomizer->getBytes(4);
        $localPart = strtolower(bin2hex($randomBytes));
        return $localPart . '@' . $domainName;
    }
}

$this->randomizer is the PHP 8 Randomizer instance

You'll also need to load your extension into Faker

faker()->resolveExtensions([CustomEmailExtension::class])

Registering your extension once and for all

resolveExtensions() has to run before every generation, which quickly becomes tedious when the extension is used across the whole application. Instead, you can wrap your extensions in a service provider and declare it in the extra.faker section of your project's composer.json — Faker discovers it on its own, exactly like it does for installed packages:

"extra": {
    "faker": {
        "providers": [
            "App\\Faker\\AppFakerServiceProvider"
        ]
    }
},

See project discovery for the details.


Copyright © 2026