Skip to content

Commit a4aad53

Browse files
committed
Add documentation for property hooks.
1 parent 60898a5 commit a4aad53

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

docs/en/reference/basic-mapping.rst

+66
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,8 @@ These are the "automatic" mapping rules:
214214
| Any other type | ``Types::STRING`` |
215215
+-----------------------+-------------------------------+
216216

217+
.. versionadded:: 2.11
218+
217219
As of version 2.11 Doctrine can also automatically map typed properties using a
218220
PHP 8.1 enum to set the right ``type`` and ``enumType``.
219221

@@ -224,6 +226,70 @@ and a custom ``Doctrine\ORM\Mapping\TypedFieldMapper`` implementation.
224226

225227
:doc:`Read more about TypedFieldMapper <typedfieldmapper>`.
226228

229+
Property Hooks
230+
--------------
231+
232+
.. versionadded:: 3.4
233+
234+
Doctrine supports mapping hooked properties as long as they have a backed property
235+
and are not virtual.
236+
237+
238+
.. configuration-block::
239+
240+
.. code-block:: attribute
241+
242+
<?php
243+
use Doctrine\ORM\Mapping\Column;
244+
use Doctrine\DBAL\Types\Types;
245+
246+
#[Entity]
247+
class Message
248+
{
249+
#[Column(type: Types::INTEGER)]
250+
private $id;
251+
#[Column(type: Types::STRING)]
252+
public string $language = 'de' {
253+
// Override the "read" action with arbitrary logic.
254+
get => strtoupper($this->language);
255+
256+
// Override the "write" action with arbitrary logic.
257+
set {
258+
$this->language = strtolower($value);
259+
}
260+
}
261+
}
262+
263+
.. code-block:: xml
264+
265+
<doctrine-mapping>
266+
<entity name="Message">
267+
<field name="id" type="integer" />
268+
<field name="language" />
269+
</entity>
270+
</doctrine-mapping>
271+
272+
If you attempt to map a virtual property with `#[Column]` an exception will be thrown.
273+
274+
Some caveats apply to the use of property hooks, as they behave differently when accessing the property through
275+
the entity or directly through DQL/EntityRepository. Because the property hook can modify the value of the property in a way
276+
that value and raw value are different, you have to use the raw value representation when querying for the property.
277+
278+
.. code-block:: php
279+
280+
<?php
281+
$queryBuilder = $entityManager->createQueryBuilder();
282+
$queryBuilder->select('m')
283+
->from(Message::class, 'm')
284+
->where('m.language = :language')
285+
->setParameter('language', 'de'); // Use lower case here for raw value representation
286+
287+
$query = $queryBuilder->getQuery();
288+
$result = $query->getResult();
289+
290+
$messageRepository = $entityManager->getRepository(Message::class);
291+
$deMessages = $messageRepository->findBy(['language' => 'de']); // Use lower case here for raw value representation
292+
227293
.. _reference-mapping-types:
228294

229295
Doctrine Mapping Types

0 commit comments

Comments
 (0)