noahlvb/valueobject-bundle

Symfony integration for my value object package

v2.0.0 2022-04-30 20:14 UTC

This package is auto-updated.

Last update: 2024-04-29 05:16:10 UTC


README

Symfony intergation for my value object package

CI Latest Stable Version License

Installation

With composer, add:

$ composer require noahlvb/valueobject-bundle

Run Tests

To make sure everything works you can run tests:

$ make test

Doctrine DBAL

In order to store you own value object just make a new doctrine type extended by ValueObjectType. Also add this newly created type to your doctrine config.

class EmailAddressType extends ValueObjectType
{
    public function getClassName(): string
    {
        return EmailAddress::class;
    }

    public function getName(): string
    {
        return 'email_address';
    }
}
doctrine:
    dbal:
        types:
          email_address: SoulSurvivor\Integration\Doctrine\Persistence\Type\ValueEmailAddressType

Symfony Forms

If you want to use your value object in a Symfony Form you should make a new form type extending ValueObjectForm. And then use that formType in your own form.

class EmailAddressForm extends ValueObjectForm
{
    protected function getClassName(): string
    {
        return EmailAddress::class;
    }
}

By default ValueObjectForm will be a TextType. If you wish to override this and make it a EmailType for example, override the getParent() method with your choose.

class EmailAddressForm extends ValueObjectForm
{
    protected function getClassName(): string
    {
        return EmailAddress::class;
    }

    public function getParent()
    {
        return EmailType::class;
    }
}

Symfony Validator

By default the ValeuObjectForm will use the ValueObjectConstraint(Validator) when validating the form. This will use the build in isValid() method of the value objects. If you wish to write your own validation message or extend the validator you can do so in like this.

class EmailAddressConstraint extends ValueObjectConstraint
{
    public $message = 'This email address is not valid.';
}
class EmailAddressConstraintValidator extends ValueObjectConstraintValidator
{
}

You have the create a empty class and extend the ValueObjectConstraintValidator. This is because Symfony Validator matches the constraint and its validator based on the class names.

Lastly in your form type override the getConstraintClassName() with the class name of your newly created constraint. Like this:

class EmailAddressForm extends ValueObjectForm
{
    protected function getConstraintClassName(): string
    {
        return EmailAddressConstraint::class;
    }
}