Last active
August 17, 2017 11:50
-
-
Save Ocramius/f8504800183cf0210793 to your computer and use it in GitHub Desktop.
Association lazy-loading with Zend\Db
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use ProxyManager\Factory\LazyLoadingValueHolderFactory; | |
use Zend\Stdlib\Hydrator\HydratorInterface; | |
class BlogPostHydrator implements HydratorInterface | |
{ | |
/** | |
* @var HydratorInterface | |
*/ | |
private $wrappedHydrator; | |
/** | |
* @var UserTable | |
*/ | |
private $userTable; | |
/** | |
* @var LazyLoadingValueHolderFactory | |
*/ | |
private $proxyFactory; | |
public function __construct( | |
HydratorInterface $wrappedHydrator, | |
UserTable $userTable, | |
LazyLoadingValueHolderFactory $proxyFactory | |
) { | |
$this->wrappedHydrator = $wrappedHydrator; | |
$this->userTable = $userTable; | |
$this->proxyFactory = $proxyFactory; | |
} | |
/** | |
* {@inheritDoc} | |
*/ | |
public function extract($object) | |
{ | |
// ... not covered in this example | |
} | |
/** | |
* {@inheritDoc} | |
*/ | |
public function hydrate(array $data, $object) | |
{ | |
if (isset($data['author_id'])) { | |
$data['author'] = $this->buildAuthorProxy($data['author_id']); | |
} | |
return $this->wrappedHydrator->hydrate($data, $object); | |
} | |
private function buildAuthorProxy($id) | |
{ | |
$this->proxyFactory->createProxy( | |
'User', | |
function (& $wrappedObject, $proxy, $method, $parameters, & $initializer) use ($id) { | |
$initializer = null; | |
$wrappedObject = $this->userTable->findUser($id); | |
return true; | |
} | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use ProxyManager\Factory\LazyLoadingValueHolderFactory; | |
$blogPostHydrator = new BlogPostHydrator(new ClassMethods(), $userTable, new LazyLoadingValueHolderFactory()); | |
$data = [ | |
'title' => 'Stuff', | |
'content' => 'Lorem ipsum dolor....', | |
'author_id' => 123, | |
]; | |
$blogPost = $blogPostHydrator->hydrate($data, new BlogPost()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment