|
| 1 | +## Parameter Validation |
| 2 | + |
| 3 | +### Validation via the `validate` Method |
| 4 | + |
| 5 | +The `Serialize` class provides a `validate` method that is automatically called when an object is created using the `from` method. You can implement custom data validation logic within this method. |
| 6 | + |
| 7 | +Here's an example: |
| 8 | + |
| 9 | +```php |
| 10 | +use Astral\Serialize\Serialize; |
| 11 | + |
| 12 | +class TestConstructValidationFromSerialize extends Serialize |
| 13 | +{ |
| 14 | + public string $type_string; |
| 15 | + |
| 16 | + /** |
| 17 | + * Data validation method |
| 18 | + * Automatically called after object creation via the from method |
| 19 | + */ |
| 20 | + public function validate(): void |
| 21 | + { |
| 22 | + // Validate the value of the type_string property |
| 23 | + if ($this->type_string !== '123') { |
| 24 | + throw new Exception('type_string must be equal to 123'); |
| 25 | + } |
| 26 | + |
| 27 | + // You can also modify property values |
| 28 | + $this->type_string = '234'; |
| 29 | + } |
| 30 | +} |
| 31 | +``` |
| 32 | + |
| 33 | +### Validation in `__construct` |
| 34 | + |
| 35 | +When creating objects directly using the `__construct` method, you can implement parameter validation logic in the constructor. However, note that this approach can only access properties defined in the constructor and cannot access other properties. |
| 36 | + |
| 37 | +```php |
| 38 | +use Astral\Serialize\Serialize; |
| 39 | + |
| 40 | +class TestConstructFromSerialize extends Serialize |
| 41 | +{ |
| 42 | + // Note: This property cannot be accessed in the constructor |
| 43 | + // If you need to validate this property, use the validate method |
| 44 | + public string $not_validate_string; |
| 45 | + |
| 46 | + /** |
| 47 | + * Parameter validation in the constructor |
| 48 | + * @param string $type_string The input string parameter |
| 49 | + */ |
| 50 | + public function __construct( |
| 51 | + public string $type_string, |
| 52 | + ) { |
| 53 | + // Validate the input parameter |
| 54 | + if ($this->type_string !== '123') { |
| 55 | + throw new Exception('type_string must be equal to 123'); |
| 56 | + } |
| 57 | + |
| 58 | + // Modify the property value |
| 59 | + $this->type_string = '234'; |
| 60 | + } |
| 61 | +} |
0 commit comments