doudou8783 2012-10-17 14:27
浏览 67
已采纳

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

I have an Attachment Entity in Doctrine which references a file on Amazon S3. I need to be able to provide a sort of 'Calculated Field' on the Entity that works out what I call the downloadpath. The downloadpath would be a calculated URL, for example http://site.s3.amazon.com/%s/attach/%s where I need to replace the two string values with values on the entity itself (account and filename), so;

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

Although we use a Service Layer, I'd like the downloadpath to be available on the Entity at all times without it having to pass through the SL.

I've considered the obvious route of adding say a constant to the Entity;

const DOWNLOAD_PATH = 'http://site.s3.amazon.com/%s/attach/%s'; and a custom getDownloadPath() but I'd like to keep specifics like this URL in my app's configuration, not the Entities class (also, see update below)

Does anyone have any ideas on how I could achieve this?

UPDATE To add to this, I am aware now that I would need to generate a temporary URL with the AmazonS3 library to allow temporary authed access to the file - I'd prefer not to make a static call to our Amazon/Attachment Service to do this as It just doesn't feel right.

  • 写回答

1条回答 默认 最新

  • duan198409 2012-10-18 14:55
    关注

    Turns out the cleanest way to do this is using the postLoad event like so;

    <?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));
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 fluent无法启动
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架
  • ¥15 有关sql server business intellige安装,包括SSDT、SSMS。