PHPackages                             natitech/builder-generator - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. natitech/builder-generator

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

natitech/builder-generator
==========================

PHP standalone library to generate a builder (pattern) from a class

2.2.0(3y ago)427MITPHPPHP ^7.4|^8.0

Since Aug 31Pushed 3y ago1 watchersCompare

[ Source](https://github.com/natitech/builder-generator)[ Packagist](https://packagist.org/packages/natitech/builder-generator)[ RSS](/packages/natitech-builder-generator/feed)WikiDiscussions master Synced today

READMEChangelog (7)Dependencies (7)Versions (9)Used By (0)

Builder generator
=================

[](#builder-generator)

[![License](https://camo.githubusercontent.com/2b699847223c2f1aa704733f0f70418e17e6490b17aa2b1833b8df66a1d8f4c9/68747470733a2f2f706f7365722e707567782e6f72672f6e617469746563682f6275696c6465722d67656e657261746f722f6c6963656e7365)](https://packagist.org/packages/natitech/builder-generator)

PHP standalone library to generate a [builder pattern](https://en.wikipedia.org/wiki/Builder_pattern) from a class.

Installation
------------

[](#installation)

By using composer on your project or globally

```
composer require natitech/builder-generator
composer global require natitech/builder-generator
```

Usage
-----

[](#usage)

You can use the binary to generate a builder near a class :

```
/path/to/vendor/bin/generate-builder /path/to/class
```

OR you can use it inside another PHP script :

```
\Nati\BuilderGenerator\FileBuilderGenerator::create()->generateFrom('/path/to/class');
```

What will be generated
----------------------

[](#what-will-be-generated)

This will generate a builder class aside the built class.

Example :

```
//From /path/to/MyClass.php file = the built class
class MyClass {
    public int $id;

    public string $label;
}

//This new file /path/to/MyClassBuilder.php will be generated = the builder class
class MyClassBuilder {
    private int $id;

    private string $label;

    public function __construct(Faker $faker)
    {
        $this->id = $faker->number();
        $this->label = $faker->word;
    }

    public function build(): MyClass
    {
        $myClass = new MyClass();
        $myClass->id = $this->id;
        $myClass->label = $this->label;

        return $myClass;
    }

    //this will have to be generated by your IDE
    public function withLabel(string $label): self
    {
        $this->label = $label;

        return $this;
    }
}

//The ultimate goal is to use this in tests
/** @test */
public function canTestSomething()
{
    $this->assertEquals(
        'test',
        $this->service->something($this->myClass()->withLabel('used in test')->build())
    );
}

private function myClass(): MyClassBuilder
{
    return new MyClassBuilder(Faker\Factory::create());
}
```

The builder class may need to receive updates on codestyle, faker usages, infered types, namespace, etc. Also, to avoid producing unused code, there are no setters for builder properties. Your IDE should be able to easily fix all of that.

The generator will try to detect property types (php types, phpdoc types, doctrine orm attributes or annotations) and will try to detect the appropriate faker method based on the type and the name of the properties.

Faker
-----

[](#faker)

You can use the --faker option to try to set the most relevant values. In that case, [Faker](https://fakerphp.github.io) will be used as a dependency of the builder class.

Build strategies
----------------

[](#build-strategies)

There are many strategies to build a class : public properties, setter (fluent or not), constructor. A brief explanation on each strategies is given below, but you might prefer read unit tests to fully understand them.

By default, the generator will try to detect the most used strategy inside the built class and will use it for the entire builder class. If you are using setters on all properties but one, the generator will use setters on properties that support it and ignore the property that does not.

But you can also explictly pass a strategy using the '--strategy' option.

### Public strategy

[](#public-strategy)

When properties are public. See example above.

### Constructor strategy

[](#constructor-strategy)

When properties are protected/private and set inside the \_\_construct method.

```
//Built class
class MyClass {
    private int $id;

    public function __construct(int $id, private string $label)
    {
        $this->id = $id;
    }
}

//Builder class
class MyClassBuilder {
    private int $id;

    private string $label;

    public function __construct(Faker $faker)
    {
        $this->id = $faker->number();
        $this->label = $faker->word;
    }

    public function build(): MyClass
    {
        return new MyClass(
            $this->id,
            $this->label
        );
    }
}
```

### Setter strategy

[](#setter-strategy)

When properties are protected/private but can be set using public setters. The setters can be fluent or not.

```
//Built class
class MyClass {
    protected int $id;

    protected string $label;

    public function setId(int $id)
    {
        $this->id = $id;

        return $this;
    }

    public function setLabel(string $label)
    {
        $this->label = $label;

        return $this;
    }
}

//Builder class
class MyClassBuilder {
    private int $id;

    private string $label;

    public function __construct(Faker $faker)
    {
        $this->id = $faker->number();
        $this->label = $faker->word;
    }

    public function build(): MyClass
    {
        return (new MyClass())
            ->setId($this->id)
            ->setLabel($this->label);
    }
}
```

### Build method strategy

[](#build-method-strategy)

This is a less conventionnal way to build a class. In that case, properties are protected/private and set by public domain methods. So, there is no easy way to set the built class in a certain state. If, for test purposes, you want to be able to quickly set the state of that object properties by properties, a solution is to add a static build() method in the built class.

```
//Built class
class MyClass {
    private int $id;

    private ?string $label = null;

    public static function create(int $id): self
    {
        $myClass = new self();
        $myClass->id = $id;

        return $myClass;
    }

    public function updateLabel(string $label): self
    {
        $this->label = $label;

        return $this;
    }

    //This method will have to be generated by you IDE from the builder class
    //It allows you to hack the state of this object without relying on its public interface
    public static function build(int $id, string $label): self
    {
        $myClass = new self();
        $myClass->id = $this->id;
        $myClass->label = $this->label;

        return $myClass;
    }
}

//Builder class
class MyClassBuilder {
    private int $id;

    private string $label;

    public function __construct(Faker $faker)
    {
        $this->id = $faker->number();
        $this->label = $faker->word;
    }

    public function build(): MyClass
    {
        return MyClass::build(
            $this->id,
            $this->label
        );
    }
}
```

### Custom strategy / contributions

[](#custom-strategy--contributions)

To create a custom strategy :

- you need to implement `Nati\BuilderGenerator\Property\PropertyBuildStrategy`and add it to `Nati\BuilderGenerator\Property\PropertyBuildStrategyCollection`. This will decide HOW properties are built.
- you also need to complete `\Nati\BuilderGenerator\Analyzer\BuildableClassAnalyzer::getWriteStrategies()`. This will decide WHEN properties could be built with this strategy.

IDE / PHPStorm
--------------

[](#ide--phpstorm)

You can use this tool as an external tool in your IDE.

For PHPStorm user, see . Example configuration :

- Name : Generate builder
- Description : Generate a builder class from a PHP class
- Program : /path/to/your/home/.composer/vendor/bin/generate-builder
- Arguments : $FilePath$
- Working directory : $FileDir$

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~159 days

Recently: every ~276 days

Total

8

Last Release

1333d ago

Major Versions

1.4.0 → 2.0.02022-08-25

PHP version history (2 changes)1.0.0PHP ^7.3

2.0.0PHP ^7.4|^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/46979928?v=4)[Antoine ROLLAND](/maintainers/natitech)[@natitech](https://github.com/natitech)

---

Top Contributors

[![natitech](https://avatars.githubusercontent.com/u/46979928?v=4)](https://github.com/natitech "natitech (2 commits)")

---

Tags

builder-design-patternbuilder-patternphpphp-libraryphp-standalone-library

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/natitech-builder-generator/health.svg)

```
[![Health](https://phpackages.com/badges/natitech-builder-generator/health.svg)](https://phpackages.com/packages/natitech-builder-generator)
```

###  Alternatives

[icanhazstring/composer-unused

Show unused packages by scanning your code

1.7k7.0M188](/packages/icanhazstring-composer-unused)[phpro/soap-client

A general purpose SoapClient library

8885.6M46](/packages/phpro-soap-client)[roave/backward-compatibility-check

Tool to compare two revisions of a public API to check for BC breaks

5953.3M56](/packages/roave-backward-compatibility-check)[coenjacobs/mozart

Composes all dependencies as a package inside a WordPress plugin

4723.6M20](/packages/coenjacobs-mozart)[cognesy/instructor-php

The complete AI toolkit for PHP: unified LLM API, structured outputs, agents, and coding agent control

310107.9k1](/packages/cognesy-instructor-php)[symfony/ai-platform

PHP library for interacting with AI platform provider.

51927.7k136](/packages/symfony-ai-platform)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
