我遇到过很多次这个问题,但直到现在我才想学习最好的方法。
假设我有一个图像实体,它有一个“路径”属性,用于存储图像文件的相对路径。例如,图像的“路径”为“20141129/123456789.jpg”。
在parameters.yml中,我设置了存放图片文件的目录的绝对路径。像这样:
image_dir: %user_static%/images/galery/
我想将“getFullPath()”方法添加到 Image 实体,在该实体中,“image_dir”参数将与“path”属性连接。我不想在 Controller 中进行串联,因为我会经常使用它。此外,我不想将图像目录插入到图像的“路径”属性中,因为我稍后可能会更改图像目录路径(这意味着我必须更新数据库中所有图像的“路径”)。
那么如何将参数注入(inject) Image 实体,以便 getFullPath() 可以使用它呢?由于 Image 实体将通过存储库方法获取而不是创建 Image 的新实例,因此将变量传递给构造方法将不起作用。
或者有更优雅的方法吗?我只希望图像实体具有 getFullPath() 方法,并且我将通过存储库方法(find、findBy...)和查询构建器获取图像。
最佳答案
您可以监听 postLoad
事件并在其中设置图像目录,以便稍后调用 getFullPath()
时它可以返回图像的连接字符串目录和路径。
postLoad 监听器
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);
}
}
服务.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 }
图像模型
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);
}
}
关于symfony - 向实体注入(inject)参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27203246/