向实体注入参数

Tac*_*aza 2 symfony doctrine-orm

我多次遇到这个问题,但直到现在我才想学习最好的方法。

假设我有一个 Image 实体,它有一个 'path' 属性,它存储图像文件的相对路径。例如,图像的“路径”为“20141129/123456789.jpg”。

在 parameters.yml 中,我设置了存储图像文件的目录的绝对路径。像这样:

image_dir: %user_static%/images/galery/
Run Code Online (Sandbox Code Playgroud)

我想将方法​​ 'getFullPath()' 添加到 Image 实体,其中 'image_dir' 参数将与 'path' 属性连接。我不想在控制器中进行连接,因为我会经常使用它。此外,我不想将图像目录插入到图像的“路径”属性中,因为稍后我可能会更改图像目录路径(这意味着我必须更新数据库中所有图像的“路径”)。

那么如何将参数注入到 Image 实体中,以便 getFullPath() 可以使用它呢?由于 Image 实体将由存储库方法获取而不是创建 Image 的新实例,因此将变量传递给构造方法将不起作用。

或者有更优雅的方法吗?我只希望图像实体具有 getFullPath() 方法,并且我将通过存储库方法(find、findBy...)和查询构建器获取图像。

qoo*_*mao 5

您可以侦听学说postLoad事件并在其中设置图像目录,以便稍后调用getFullPath()它时可以返回图像目录和路径的连接字符串。

postLoad listener

namespace Acme\ImageBundle\Doctrine\EventSubscriber;

use Acme\ImageBundle\Model\ImageInterface;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;

class ImageDirectorySubscriber implements EventSubscriber
{
    protected $imageDirectory;

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

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

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

        if (!$image instanceof ImageInterface) {
            return;
        }

        $image->setImageDirectory($this->imageDirectory);
    }
}
Run Code Online (Sandbox Code Playgroud)

services.yml

parameters:
    acme_image.subscriber.doctrine.image_directory.class:
            Acme\ImageBundle\Doctrine\EventSubscriber\ImageDirectorySubscriber

services:
    acme_image.subscriber.doctrine.image_directory:
        class: %acme_image.subscriber.doctrine.image_directory.class%
        arguments:
            - %acme_image.image_directory%
        tags:
            - { name: doctrine.event_subscriber }
Run Code Online (Sandbox Code Playgroud)

Image Model

class Image implements ImageInterface
{
    protected $path;

    protected $imageDirectory;

    .. getter and setter for path..

    public function setImageDirectory($imageDirectory)
    {
        // Remove trailing slash if exists
        $this->imageDirectory = rtrim($imageDirectory, '/');

        return $this;
    }

    public function getFullPath()
    {
        return sprintf('%s/%s', $this->imageDirectory, $this->path);
    }
}
Run Code Online (Sandbox Code Playgroud)