-
Notifications
You must be signed in to change notification settings - Fork 1
Extending value objects via enrichment
Value objects can be enriched with PHP traits.
Create a folder in the root of your project called enrichments
. You can configure the location of your enrichments folder using a configuration file.
Place PHP traits within your enrichments folder. Then use PHP 8 attributes to link them to your value objects. For example, if you had a value object called MyValueObject
you can enrich it like this:
<?php
declare(strict_types=1);
namespace MyProject\Enrichments;
use ChrisHarrison\VoGenerator\Attributes\Enriches;
#[Enriches('MyValueObject')]
trait MyValueObjectEnrichment
{
public function full(): string
{
return "{$this->root()->toNative()}/{$this->name()->toNative()}";
}
}
When you regenerate your value objects (vendor/bin/vogen
), the full
method provided by the trait will be available in your MyValueObject
.
Value objects can define hooks on their methods. For example, the value objects that ship with the package all have hooks in their __construct
methods.
To hook into a method in a value object, add a method to an enrichment trait that follows the format:
public function hook<<methodToHook>>(callable $inner, ...$values);
Note that underscores in method names (e.g. __construct
) are ignored.
-
$inner
is a callable that represents the original method. -
...$values
are all the original values that are passed to the method.
For example, to hook into the construct method of a value object of type string:
public function hookConstruct(callable $inner, string $value)
{
// Do something before construct
$inner($value);
// Do something after construct
}