Skip to content

Commit 6a13fb1

Browse files
committed
docs: provide better ruleset extension in types document
1 parent 5059824 commit 6a13fb1

File tree

1 file changed

+27
-7
lines changed

1 file changed

+27
-7
lines changed

docs/advanced/types.md

+27-7
Original file line numberDiff line numberDiff line change
@@ -144,19 +144,39 @@ Alternately, you could extend the class:
144144
*/
145145
class TransactionForm extends RuleSet
146146
{
147-
public function __construct($options)
147+
public function __construct()
148148
{
149-
$actualOptions = new ResultSetOptions();
150-
$actualOptions->setResultSetClass(TransactionFormResult::class);
151-
foreach($options->rules() as $rule) {
152-
$actualOptions->addRule($rule);
153-
}
149+
$options = new ResultSetOptions();
150+
$options->setResultSetClass(TransactionFormResult::class);
151+
$options->addRule(/* ... */);
154152

155-
parent::__construct($actualOptions);
153+
parent::__construct($options);
156154
}
157155
}
158156
```
159157

158+
> Setting the options explicitly in the constructor of the extending class ensures you know the state.
159+
> If you want to prevent child classes redefining the constructor and changing the semantics and behavior of your ruleset, create a named constructor:
160+
>
161+
> ```php
162+
> /**
163+
> * @template-extends RuleSet<TransactionFormResult>
164+
> */
165+
> class TransactionForm extends RuleSet
166+
> {
167+
> public static function create(): self
168+
> {
169+
> $options = new ResultSetOptions();
170+
> $options->setResultSetClass(TransactionFormResult::class);
171+
> $options->addRule(/* ... */);
172+
>
173+
> return new self($options);
174+
> }
175+
> }
176+
> ```
177+
>
178+
> Alternately, you can also make your constructor `final`.
179+
160180
If you are creating an anonymous class extending `RuleSet`, use the `@template-extends` annotation:
161181
162182
```php

0 commit comments

Comments
 (0)