oliverdavies.uk/content/node.43311430-52e8-4fe6-8dd4-ab7d158adafa.yml

183 lines
6.2 KiB
YAML

uuid:
- value: 43311430-52e8-4fe6-8dd4-ab7d158adafa
langcode:
- value: en
type:
- target_id: daily_email
target_type: node_type
target_uuid: 8bde1f2f-eef9-4f2d-ae9c-96921f8193d7
revision_timestamp:
- value: '2025-07-01T22:29:08+00:00'
revision_uid:
- target_type: user
target_uuid: b8966985-d4b2-42a7-a319-2e94ccfbb849
revision_log: { }
status:
- value: true
uid:
- target_type: user
target_uuid: b8966985-d4b2-42a7-a319-2e94ccfbb849
title:
- value: 'An example of generics in PHP'
created:
- value: '2025-06-29T22:20:18+00:00'
changed:
- value: '2025-07-01T22:29:08+00:00'
promote:
- value: false
sticky:
- value: false
default_langcode:
- value: true
revision_translation_affected:
- value: true
path:
- alias: /daily/2025/06/29/example-generics-php
langcode: en
body:
- value: |-
Unfortunately, unlike other languages like Go and TypeScript, generics aren't supported in PHP, but they are possible with static analysis tools like PHPStan and Psalm.
I use generics as they allow me to make code more reusable whilst still being robust.
For example, if I created a Collection class to represent the guests for a podcast episode, it could look like this:
```php
<?php
/**
* @implements \IteratorAggregate<mixed>
*/
class Guests implements \IteratorAggregate {
/**
* @param Guest[] $guests
*/
public function __construct(private array $guests) {
}
public function count(): int {
return count($this->items);
}
public function first(): Guest {
return array_values($this->items)[0];
}
public function getIterator(): \Traversable {
return new \ArrayIterator($this->items);
}
}
```
Note: the idea of using `IteratorAggregate` came from [from Dan Leech][1] and his talk at a local PHP meetup.
Each contains an array of `Guest` objects that I can run methods like `count()` and `first()` on.
Everything is typed so PHPStan can parse the code and provide as much assistance as possible.
But, what if I wanted to make a generic Collection that could accept any type of item?
That's where generics are useful.
First, I need to define a template:
```php
/**
* @implements \IteratorAggregate<mixed>
* @template T
*/
```
Now `T` is defined, I can use it in place of the original `Guest` types:
```php
/**
* @param T[] $items
*/
public function __construct(private array $items) {
}
/**
* @return T|null
*/
public function first(): mixed {
return array_values($this->items)[0];
}
```
This says that the Collection accepts an array of `T` items and returns either a `T` or null.
`T` could be a `Guest`, a `NodeInterface` or anything else.
But, whatever it is, either a null value or the same type is returned.
Generics means that PHPStan can continue to give the most detailed analysis, my language server can give the best completion and diagnostics, and the code is flexible and easy to reuse.
Hopefully, generics will be a core PHP feature but, until then, the same benefits can be found from static analysis tools.
[1]: /daily/2025/03/29/collections
format: markdown
processed: |
<p>Unfortunately, unlike other languages like Go and TypeScript, generics aren't supported in PHP, but they are possible with static analysis tools like PHPStan and Psalm.</p>
<p>I use generics as they allow me to make code more reusable whilst still being robust.</p>
<p>For example, if I created a Collection class to represent the guests for a podcast episode, it could look like this:</p>
<pre><code>&lt;?php
/**
* @implements \IteratorAggregate&lt;mixed&gt;
*/
class Guests implements \IteratorAggregate {
/**
* @param Guest[] $guests
*/
public function __construct(private array $guests) {
}
public function count(): int {
return count($this-&gt;items);
}
public function first(): Guest {
return array_values($this-&gt;items)[0];
}
public function getIterator(): \Traversable {
return new \ArrayIterator($this-&gt;items);
}
}
</code></pre><p>Note: the idea of using <code>IteratorAggregate</code> came from <a href="/daily/2025/03/29/collections">from Dan Leech</a> and his talk at a local PHP meetup.</p>
<p>Each contains an array of <code>Guest</code> objects that I can run methods like <code>count()</code> and <code>first()</code> on.</p>
<p>Everything is typed so PHPStan can parse the code and provide as much assistance as possible.</p>
<p>But, what if I wanted to make a generic Collection that could accept any type of item?</p>
<p>That's where generics are useful.</p>
<p>First, I need to define a template:</p>
<pre><code>/**
* @implements \IteratorAggregate&lt;mixed&gt;
* @template T
*/
</code></pre><p>Now <code>T</code> is defined, I can use it in place of the original <code>Guest</code> types:</p>
<pre><code>/**
* @param T[] $items
*/
public function __construct(private array $items) {
}
/**
* @return T|null
*/
public function first(): mixed {
return array_values($this-&gt;items)[0];
}
</code></pre><p>This says that the Collection accepts an array of <code>T</code> items and returns either a <code>T</code> or null.</p>
<p><code>T</code> could be a <code>Guest</code>, a <code>NodeInterface</code> or anything else.</p>
<p>But, whatever it is, either a null value or the same type is returned.</p>
<p>Generics means that PHPStan can continue to give the most detailed analysis, my language server can give the best completion and diagnostics, and the code is flexible and easy to reuse.</p>
<p>Hopefully, generics will be a core PHP feature but, until then, the same benefits can be found from static analysis tools.</p>
summary: ''
field_daily_email_cta:
- target_type: node
target_uuid: c74de3cf-5362-4d08-935a-a9d0d22fcb94