amtgard/builder-traits

Builder traits

v2.0.2 2025-05-29 21:11 UTC

This package is auto-updated.

Last update: 2025-05-29 21:13:28 UTC


README

Implements a Lombokish version of Builder using Traits.

Supports the following traits individually:

  • Builder
  • Getter
  • Setter
  • ToBuilder
  • Data

Example usage is in tests/Models/ and tests/BuilderTest.php.

Builder

To add builder functionality, add the Builder trait:

use Builder;

You can then construct an object using the builder fluent interface:

Gato::builder()->age(7)->name("Charlie")->build();

Getter, Setter, Data

You can add getters and setters over all private members by adding the Getter or Setter traits.

Due to limitations in library design, both Getter and Setter cannot be used in the same class.

Instead, use the Data trait.

Getter

class Gato {
    use Getter;
    private $name;
}

$catName = $gato->getName();

Setter

class Gato {
    use Setter;
    private $name;
}
$name = $gato->getName();

Data

Due to trait method collision, we can't compose Getter and Setter in the same class.

Instead use the Data trait.

class Gato {
    use Data;
    private $name;
}
$gato->setName('Charlie');
$name = $gato->getName();

ToBuilder

We can mutate an existing object with the ToBuilder trait.

class Gato {
    use ToBuilder;
    private $name;
}
$chuck = $gato->toBuilder()->name('Charlie')->build();

Hooks

#[PostInit] Attribute

Apply the #[PostInit] attribute to any private method to be called during the ->build() phase of the Builder.