outeredge
outeredge

Reputation: 285

Implementing a Custom Field on a Doctrine Entity

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.

Upvotes: 0

Views: 1165

Answers (1)

outeredge
outeredge

Reputation: 285

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));
        }
    }
}

Upvotes: 2

Related Questions