2017-07-19 68 views
0

聚集水合器能嵌套嗎?如果我有以下類:zf2 - 嵌套聚集體水化器

class Appointment{ 
    public date; 
    public startTime; 
    public endTime; 
    public User; //* @var User */ 
} 

class User{ 
    public Location; //* @var Location*/ 
} 

...被填充了以下AggregateHydrator(從工廠創建):

class AppointmentModelHydratorFactory implements FactoryInterface 
{ 
    public function createService(ServiceLocatorInterface $serviceLocator) { 
     $serviceManager = $serviceLocator->getServiceLocator(); 
     $arrayHydrator = new ArraySerializable(); 
     $arrayHydrator->addStrategy('date', new DateTimeStrategy()) 
      ->addStrategy('endTime', new TimeStrategy()) 
      ->addStrategy('startTime', new TimeStrategy()); 

     $aggregateHydrator = new AggregateHydrator(); 
     $aggregateHydrator->add($arrayHydrator); 
     $aggregateHydrator->add($serviceLocator->get('Hydrator\User')); 
     return $aggregateHydrator; 
    } 
} 

隨着UserHydratorFactory看起來像:

class UserHydratorFactory implements FactoryInterface 
{ 
    public function createService(ServiceLocatorInterface $serviceLocator) { 
     $sm = $serviceLocator->getServiceLocator(); 
     $userHydrator = new UserHydrator($sm->get('User\Mapper')); 
     $aggregateHydrator = new AggregateHydrator(); 
     $aggregateHydrator->add($userHydrator); 
     $aggregateHydrator->add($sm->get('HydratorManager')->get('Hydrator\User\Location')); 
     return $aggregateHydrator; 
} 

}

這是拋出一個期望,因爲模型返回爲null,但我我註釋了將位置水合器添加到用戶水合器,它工作正常(雖然沒有位置數據加載)。所以我想知道聚合水合器是否可以嵌套?

回答

0

它不是內置的,但可行的。

namespace Hydrator; 
use Zend\Stdlib\Hydrator\HydratorInterface; 
class NestedHydrator implements HydratorInterface 
{ 
    protected $inner_hydrator; 
    private $empty; 


    public function __construct ($inner_hydrator, $empty) 
    { 
     $this->inner_hydrator = $inner_hydrator; 
     $this->empty = $empty; 
    } 


    public function extract ($object) 
    { 
     return [ 
      $this->getPath() => $this->inner_hydrator->extract ($object->{$this->getPath()}) 
     ]; 
    } 


    public function hydrate (array $data, $object) 
    { 
     $object->{$this->getPath()} = $this->inner_hydrator->hydrate ($data [$this->getPath()], $this->empty); 

     return $object; 
    } 


    protected function getPath() 
    { 
     return get_class ($this->empty); 
    } 
} 

然後:

$u = new User(); 
$u->Location = "4 Clinton Rd."; 

$a = new Appointment(); 
$a->date = "yesterday"; 
$a->startTime = "7:00"; 
$a->endTime = "8:00"; 
$a->User = $u; 

$h = new AggregateHydrator(); 
$h->add (new ObjectProperty()); 
$nested = new \Hydrator\NestedHydrator(new ObjectProperty(), new User()); 
$h->add ($nested); 
$data = $h->extract ($a); 

$b = $h->hydrate ($data, new Appointment()); 
$this->assertEquals ($a, $b);