在Doctrine实体上实现自定义字段

时间:2012-10-17 14:27:35

标签: php orm doctrine-orm

我在Doctrine中有一个Attachment实体,它引用了Amazon S3上的文件。我需要能够在实体上提供一种“计算字段”,它可以解决我所谓的downloadpathdownloadpath将是一个计算的URL,例如http://site.s3.amazon.com/%s/attach/%s,我需要将两个字符串值替换为实体本身的值(帐户和文件名),所以;

http://site.s3.amazon.com/1/attach/test1234.txt

虽然我们使用服务层,但我希望downloadpath始终可以在实体上使用,而不必通过SL。

我已经考虑了向实体添加一个常量的明显路径;

const DOWNLOAD_PATH = 'http://site.s3.amazon.com/%s/attach/%s';和自定义getDownloadPath(),但我想在我的应用配置中保留此网址的详细信息,而不是实体类(另请参阅下面的更新)

有没有人对如何实现这一目标有任何想法?

更新要添加到此,我现在知道我需要使用AmazonS3库生成临时URL以允许对文件进行临时的自动访问 - 我不想制作一个静态调用我们的Amazon / Attachment Service来执行此操作,因为它感觉不对。

1 个答案:

答案 0 :(得分:2)

原来最简洁的方法是使用postLoad事件,如此;

<?php

namespace My\Listener;

use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Events;
use Doctrine\ORM\Event\LifecycleEventArgs;
use My\Entity\Attachment as AttachmentEntity;
use My\Service\Attachment as AttachmentService;

class AttachmentPath implements EventSubscriber
{
    /**
     * Attachment Service
     * @param \My\Service\Attachment $service
     */
    protected $service;

    public function __construct(AttachmentService $service)
    {
        $this->service = $service;
    }

    public function getSubscribedEvents()
    {
        return array(Events::postLoad);
    }

    public function postLoad(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();

        if ($entity instanceof AttachmentEntity) {
            $entity->setDownloadPath($this->service->getDownloadPath($entity));
        }
    }
}