Skip to content

Commit d91e286

Browse files
committed
minor symfony#8349 [PropertyAccess] Document adder and remover support (dunglas, javiereguiluz)
This PR was merged into the 2.7 branch. Discussion ---------- [PropertyAccess] Document adder and remover support Commits ------- c62a603 Minor syntax fixes e0a6f97 [PropertyAccess] Document adder and remover support
2 parents 12cb0d1 + c62a603 commit d91e286

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

components/property_access.rst

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,51 @@ see `Enable other Features`_.
321321
322322
var_dump($person->getWouter()); // array(...)
323323
324+
Writing to Array Properties
325+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
326+
327+
The ``PropertyAccessor`` class allows to update the content of arrays stored in
328+
properties through *adder* and *remover* methods.
329+
330+
.. code-block:: php
331+
332+
// ...
333+
class Person
334+
{
335+
/**
336+
* @var string[]
337+
*/
338+
private $children = array();
339+
340+
public function getChildren(): array
341+
{
342+
return $this->children;
343+
}
344+
345+
public function addChild(string $name): void
346+
{
347+
$this->children[$name] = $name;
348+
}
349+
350+
public function removeChild(string $name): void
351+
{
352+
unset($this->children[$name]);
353+
}
354+
}
355+
356+
$person = new Person();
357+
$accessor->setValue($person, 'children', array('kevin', 'wouter'));
358+
359+
var_dump($person->getChildren()); // array('kevin', 'wouter')
360+
361+
The PropertyAccess component checks for methods called ``add<SingularOfThePropertyName>()``
362+
and ``remove<SingularOfThePropertyName>()``. Both methods must be defined.
363+
For instance, in the previous example, the component looks for ``addChild()`` and
364+
``removeChild()`` methods to access to the ``children`` property.
365+
`The Inflector component`_ is used to find the singular of a property name.
366+
367+
If available, *adder* and *remover* methods have priority over a *setter* method.
368+
324369
Checking Property Paths
325370
-----------------------
326371

@@ -414,3 +459,4 @@ Or you can pass parameters directly to the constructor (not the recommended way)
414459

415460

416461
.. _Packagist: https://packagist.org/packages/symfony/property-access
462+
.. _The Inflector component: https://github.com/symfony/inflector

0 commit comments

Comments
 (0)