noahlvb / valueobject-bundle
Symfony integration for my value object package
Installs: 2 019
Dependents: 0
Suggesters: 0
Security: 0
Stars: 1
Watchers: 1
Forks: 1
Open Issues: 1
Requires
- php: ^8.0
- doctrine/dbal: ^2.10
- noahlvb/valueobject: ^1.0
- symfony/form: ^6.0
- symfony/validator: ^6.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.16
- phpunit/phpunit: ^9.0
- squizlabs/php_codesniffer: ^3.5
README
Symfony intergation for my value object package
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; } }