Documentation

CompositeNamingStrategy — Zend Framework 2 2.4.9 documentation

Zend\Stdlib

CompositeNamingStrategy

Zend\Stdlib\Hydrator\NamingStrategy\CompositeNamingStrategy allows you to specify which naming strategy should be used for each key encountered during hydration or extraction.

Basic Usage

When invoked, the following composite strategy will extract the property bar into array key foo (MapNamingStrategy) and property barBat into bar_bat (UnderscoreNamingStrategy):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 class Foo
 {
     public $bar;
     public $barBat;
 }

 $mapStrategy = new Zend\Stdlib\Hydrator\NamingStrategy\MapNamingStrategy([
     'foo' => 'bar'
 ]);

 $underscoreNamingStrategy = new Zend\Stdlib\Hydrator\NamingStrategy\UnderscoreNamingStrategy();

 $namingStrategy = new Zend\Stdlib\Hydrator\NamingStrategy\CompositeNamingStrategy([
     'bar' => $mapStrategy,
     'barBat' => $underscoreNamingStrategy,
 ]);

 $hydrator = new Zend\Stdlib\Hydrator\ObjectProperty();
 $hydrator->setNamingStrategy($namingStrategy);

 $foo = new Foo();
 $foo->bar = 123;
 $foo->barBat = 42;

 print_r($foo); // Foo Object ( [bar] => 123 [barBat] => 42 )
 print_r($hydrator->extract($foo)); // Array ( [foo] => 123 [bar_bat] => 42 )

Unfortunately, this CompositeNamingStrategy can only be used for extraction as it will not know how to handle the keys necessary for hydration (foo and bar_bat, respectively). To rectify this we have to cover the keys for both hydration and extraction in our composite strategy:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
 class Foo
 {
     public $bar;
     public $barBat;
 }

 $mapStrategy = new Zend\Stdlib\Hydrator\NamingStrategy\MapNamingStrategy([
     'foo' => 'bar'
 ]);

 $underscoreNamingStrategy = new Zend\Stdlib\Hydrator\NamingStrategy\UnderscoreNamingStrategy();

 $namingStrategy = new Zend\Stdlib\Hydrator\NamingStrategy\CompositeNamingStrategy([
     // Define both directions for the foo => bar mapping
     'bar' => $mapStrategy,
     'foo' => $mapStrategy,
     // Define both directions for the barBat => bar_bat mapping
     'barBat' => $underscoreNamingStrategy,
     'bar_bat' => $underscoreNamingStrategy,
 ]);

 $hydrator = new Zend\Stdlib\Hydrator\ObjectProperty();
 $hydrator->setNamingStrategy($namingStrategy);

 $foo = new Foo();
 $foo->bar = 123;
 $foo->barBat = 42;

 $array = $hydrator->extract($foo);

 print_r($foo); // Foo Object ( [bar] => 123 [barBat] => 42 )
 print_r($array); // Array ( [foo] => 123 [bar_bat] => 42 )

 $foo2 = new Foo();
 $hydrator->hydrate($array, $foo2);

 print_r($foo2); // Foo Object ( [bar] => 123 [barBat] => 42 )

Copyright

© 2006-2018 by Zend, a Rogue Wave Company. Made with by awesome contributors.

This website is built using zend-expressive and it runs on PHP 7.

Contacts