Skip to content

amtgard/builder-traits

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Builder Trait

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.

About

Builder traits for php classes

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • PHP 100.0%