Getting Started

Package Development

Package Development on Xefi Faker PHP

Package development is heavily inspired by Laravel which provide a really easy way to extend

Package discovery

A Faker application's packages.php file contains the list of service providers that should be loaded by Faker. However, instead of requiring users to manually add your service provider to the list, you may define the provider in the extra section of your package's composer.json file so that it is automatically loaded by Faker:

"extra": {
    "faker": {
        "providers": [
            "Xefi\\FakerNumber\\NumberServiceProvider"
        ]
    }
},

Once your package has been configured for discovery, Faker will automatically register its service providers and facades when it is installed, creating a convenient installation experience for your package's users.

Service Provider

In the service provider you are now able to register the extensions you created:

namespace Xefi\FakerNumber;

use Xefi\Faker\Providers\Provider;

class NumberServiceProvider extends Provider
{
    public function boot(): void
    {
        $this->extensions([
            NumberExtension::class,
        ]);
    }
}

Extension

Extension is your free space to generate custom methods.

namespace Xefi\Faker\Tests\Support\Extensions;

use Xefi\Faker\Extensions\Extension;

class NumberTestExtension extends Extension
{
    public function returnNumberBetween(int $min, int $max): int
    {
        return rand($min, $max);
    }
}

Auto-register methods

Be aware that methods you want to expose needs to be public otherwise Faker analyzer won't be able to find your function. If you need to create function needed for organization, put them as private or protected.

Mixin generator

Faker automatically integrates your extension registered methods in a mixin injected in the default Container. This allows the IDE to suggest your methods because the Container calls are dynamic using __call.

Locales

If your extension is available in multiple languages, you need to declare an extension for each language and specify the locale. You need to use the HasLocale trait

namespace Xefi\FakerNumber\Extensions;

use Xefi\Faker\Extensions\Extension;
use Xefi\Faker\Extensions\Traits\HasLocale;

class NameExtension extends Extension
{
    use HasLocale;

    public function getLocale(): string
    {
        return 'fr_FR';
    }
}

The extensions need to have the same name, if it's not the case you may want to specify a custom name:

namespace Xefi\FakerNumber\Extensions;

use Xefi\Faker\Extensions\Extension;
use Xefi\Faker\Extensions\Traits\HasLocale;

class NameExtension extends Extension
{
    use HasLocale;

    public function getName(): string
    {
        return 'my-extension-name';
    }

    public function getLocale(): string
    {
        return 'fr_FR';
    }
}

Copyright © 2024