Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/kelunik/builders

Generating builders for value objects.
https://github.com/kelunik/builders

builder builder-generator php php-code-generator

Last synced: 9 days ago
JSON representation

Generating builders for value objects.

Awesome Lists containing this project

README

        

# builders

This packages allows generating builders for value objects automatically. One use case is creating test objects for unit and integration tests.

## Installation

```
composer require kelunik/builders
```

## Usage

Given the following `User` object, the builder generator will generate a `UserBuilderMethods` class.

```php
id;
}

public function setId(?string $id): void
{
$this->id = $id;
}

public function getName(): ?string
{
return $this->name;
}

public function setName(?string $name): void
{
$this->name = $name;
}
}
```

```php
entity = new Example\User;
}

final public function withId(?string $value)
{
$this->entity->setId($value);

return $this;
}

final public function withName(?string $value)
{
$this->entity->setName($value);

return $this;
}

final public function build(): Example\User
{
return $this->entity;
}
}
```

### Custom Builder Methods

In order to use the generated classes, you're advised to create a `UserBuilder` object that extends the generated `UserBuilderMethods`.
This separation allow you to add custom builder methods without affecting the builder generator when it throws away the old `UserBuilderMethods` and generates a new one.

```php
withId(1)->withName('root');
}
}
```

### Builder Consumption

Building test objects is easiest if you add a `builders.php` defining functions as shortcuts.

```php
root()->withName('kelunik'));

var_dump($user instanceof User);
var_dump($user);
```

### Code Generation

The code generator can be invoked with the following command, paths are relative to the composer root directory:

```
vendor/bin/builder-generator App\NamespaceOfValueObjects src src-generated
```