Zend Framework 2に基づいてApigility駆動のアプリケーションを開発しています。
現在、データベースで取得したデータをクライアントに直接送信しています。リクエストが来ると、MyResource#fetch(...)
またはMyResource#fetchAll(...)
がトリガーされ、MyService
クラスで適切なメソッドが呼び出さMyMapper
れ、 のようなメソッドでデータを取得するために呼び出されfindFooByBar(...)
ます。
応答が送信される前に、データを処理したいと思います。どうやってやるの?
Apigility ZF HAL ドキュメントには、エンティティ データが取得されてからクライアントに送信されるまでの間にエンティティ データにアクセスする方法が示されています。さて、私はこれを試しました。それは醜く、そのようなタスクには多くのコードがあります。そして...うまくいきません。ただし、ここに私の試みを投稿したい:
namespace Portfolio;
...
class Module implements ApigilityProviderInterface {
private $serviceManager;
public function onBootstrap(MvcEvent $event) {
$application = $event->getTarget();
$this->serviceManager = $serviceManager = $application->getServiceManager();
$viewHelperManager = $serviceManager->get('ViewHelperManager');
$hal = $viewHelperManager->get('Hal');
$hal->getEventManager()->attach('renderEntity', array($this, 'onRenderEntity'));
$hal->getEventManager()->attach('renderCollection', array($this, 'onRenderCollection'));
}
public function onRenderEntity($event) {
$entity = $event->getParam('entity');
if ($entity->entity instanceof ProjectEntity) {
$projectEntity = $entity->entity;
$imageCollection = $this->tempCreateimagesForProject(
$event, $entity->entity->getId()
);
$projectEntity->setImages($imageCollection);
$event->setParam('entity', $projectEntity);
}
}
public function onRenderCollection($event) {
$collection = $event->getParam('collection');
$projectCollection = $collection->getCollection();
if ($projectCollection instanceof ProjectCollection) {
foreach ($projectCollection as $key => $projectItem) {
$tempProject = $projectCollection->getItem($key);
$tempProject->append(
['images' => $this->tempCreateimagesForProject($tempProject->offsetGet('id'))]
);
$projectCollection->getItem($key)->offsetSet($key, $tempProject);
}
}
}
private function tempCreateimagesForProject(Event $event, $projectId) {
$imageService = $this->serviceManager->get('Portfolio\V2\Rest\ImageService');
$imageCollection = $imageService->getImagesForProject($projectId);
return $imageCollection;
}
...
}