我一直在使用一个图像实体,当该图像实体持久化时,它使用内部方法来保存/移动/删除使用挂钩注释关联的图像文件,但我觉得该实体本身应该只是相关的获取器和设置器。
我应该将方法留在实体中还是将其移至侦听器类?
该实体具有以下方法:
但我不确定我是否喜欢这个存在于我的实体中。
/**
* @ORM\PostPersist()
* @ORM\PostUpdate()
*/
public function upload()
{
if(null === $this->getFile()) {
return;
}
// throws exception on error - stopping persist
$this->getFile()->move($this->getUploadRootDir(), $this->url);
if(isset($this->tmp)) {
unlink($this->getUploadRootDir() . '/'. $this->tmp);
$this->tmp = null;
}
$this->file = null;
}
所以我想使用下面的示例将它们移到侦听器类中,但是我不喜欢这样的想法:检查每种类型的实体是否持久并且只关心“图像”实体:
public function postPersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$entityManager = $args->getEntityManager();
if ($entity instanceof Image) {
// ... do something with the Product
}
}
这实际上取决于用例。引用烹饪书中有关如何处理文件上传的内容:
使用生命周期回调是一种受限制的技术,存在一些缺点。如果要删除Document :: getUploadRootDir()方法内的硬编码DIR引用,最好的方法是开始使用显式的教义侦听器。在那里,您将能够注入内核参数,例如kernel.root_dir,以便能够建立绝对路径。
如果您希望两全其美,则可以使用Entity Listeners。该监听器将仅在该单个实体上触发,而不是监听所有实体:
我还建议您查看可上传的学说扩展,它应该提供您需要的所有功能。
它还提供了设置默认上传路径的方法:http : //www.obverse.com/2013/03/the-trick-to-getting-gedmo-uploadable-working-with-sonata-admin/
stof_doctrine_extensions:
default_locale: en_US
uploadable:
# Default file path: This is one of the three ways you can configure the path for the Uploadable extension
default_file_path: %kernel.root_dir%/../web/uploads
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句