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

报告相同问题?

悬赏问题

  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗