如何确保加载Synfony Entity以触发postLoad事件?

时间:2015-06-01 16:43:26

标签: php symfony symfony-2.6

我是Symfony的新手并关注the Jobeet tutorial。我正在尝试使用服务侦听器和postLoad将Container注入实体。目的是使用LiipImagineBundle@ORM\PostPersist中编写缩略图图像。问题是在某些路由上未加载Job实体,然后未触发postLoad。因此,@ORM\PostPersist中使用的容器不可用。

根据教程,PostPersist运行有两条路线:

  • job/create
  • job/update

我发现未加载作业实体且postLoad未触发job/create。路线job/update很好,容器被注入。我发布了一些

的代码片段
  • services.yml
  • JobListener.php
  • 实体\ Job.php
  • JobController.php

的src / IBW / JobeetBundle /资源/配置/ services.yml

services:
    ibw.jobeet.entity.job.container_aware:
        class: Ibw\JobeetBundle\Doctrine\Event\Listener\JobListener
        calls:
            - [setContainer, ["@service_container"]]
        tags:
            - { name: doctrine.event_listener, event: postLoad }

的src / IBW / JobeetBundle /学说/事件/侦听/ JobListener.php

<?php
namespace Ibw\JobeetBundle\Doctrine\Event\Listener;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\Event\LifecycleEventArgs;

class JobListener
{
    /** @var ContainerInterface */
    protected $container;

    /**
    * @param ContainerInterface @container
    */
    public function setContainer(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * @ORM\PostLoad
     */
    public function postLoad(LifecycleEventArgs $eventArgs)
    {
        $entity = $eventArgs->getEntity();
        if (method_exists($entity, 'setContainer')) {
            $entity->setContainer($this->container);
        }
    }
}

的src / IBW / JobeetBundle /实体/ Job.php

// ....
/**
 * @ORM\PostPersist
 */
public function upload()
{
    if (null === $this->getFile()) {
        return;
    }

    if ($this->getFile()->move($this->getUploadTmpRootDir(), $this->logo)) {
        $this->moveAndResizeImage();
    }

    $this->file = null;
}

private function moveAndResizeImage($filter = 'primary')
{
    $path = $this->getWebTmpPath();
    $target = $this->getAbsolutePath();

    if (file_exists($path)) {
        $container = $this->container; 
        // got problem here. $container is null for /job/create
        // but it is okay for /job/update
        $dataManager = $container->get('liip_imagine.data.manager');
        $filterManager = $container->get('liip_imagine.filter.manager');

        $image = $dataManager->find($filter, $path); 
        $thumb = $filterManager->applyFilter($image, $filter);

        file_put_contents($target, $thumb->getContent());

        unlink($path); // remove the temp client original image
    }
}
// ...

的src / IBW / JobeetBundle /控制器/ JobController.php

// ...
public function createAction(Request $request)
{
    $entity = new Job();
    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('ibw_job_preview', array(
            'company' => $entity->getCompanySlug(),
            'location' => $entity->getLocationSlug(),
            'token' => $entity->getToken(),
            'position' => $entity->getPositionSlug()
        )));
    }

    return $this->render('IbwJobeetBundle:Job:new.html.twig', array(
        'entity' => $entity,
        'form'   => $form->createView(),
    ));
}
// ....

有什么方法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

我通过在事件监听器类中添加postPersist来解决这个问题,以确保容器在持久化之前可用。 LiipImagineBundle 服务在JobListener上调用。我将MyListener重命名为ibw.jobeet.event.mylistener: class: Ibw\JobeetBundle\Listener\Event\MyListener calls: - [setContainer, ["@service_container"]] tags: - { name: doctrine.event_listener, event: postLoad } - { name: doctrine.event_listener, event: prePersist } 。这是我的工作代码:

<强>的src / IBW / JobeetBundle /资源/配置/ services.yml

<?php
namespace Ibw\JobeetBundle\Listener\Event;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\Event\LifecycleEventArgs;

use Ibw\JobeetBundle\Entity\Job;

class MyListener
{
    /** @var ContainerInterface */
    protected $container;

    /**
    * @param ContainerInterface @container
    */
    public function setContainer(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * @param LifecycleEventArgs $eventArgs
     */
    public function postLoad(LifecycleEventArgs $eventArgs)
    {
        $this->injectContainer($eventArgs);
    }

    /**
     * @param LifecycleEventArgs $eventArgs
     */
    public function prePersist(LifecycleEventArgs $eventArgs)
    {
        $this->injectContainer($eventArgs);
    }

    protected function injectContainer(LifecycleEventArgs $eventArgs)
    {
        $entity = $eventArgs->getEntity();
        if ($entity instanceof Job) {
            $entity->setContainer($this->container);
        }

        $em = $eventArgs->getEntityManager();
        $repository = $em->getRepository('IbwJobeetBundle:Job');
        if ($entity instanceof Job) {
            $repository->setContainer($this->container);
        }
    }
}

<强>的src / IBW / JobeetBundle /监听器/活动/ MyListener.php

mydf = structure(list(User = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), 
    Mode = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), Trial1Time = c(20L, 
    5L, 40L, 10L, 15L, 30L, 13L, 11L, 35L), Trial2Time = c(30L, 
    7L, 25L, 20L, 17L, 35L, 26L, 11L, 38L)), .Names = c("User", 
"Mode", "Trial1Time", "Trial2Time"), class = "data.frame", row.names = c(NA, 
-9L))

可能有更好的方法来解决这个问题。如果有,请发一个答案。我知道注入整个容器是一种不好的做法。我将更新以便稍后注入所需的服务。