我一直在处理一个图像实体,当持久化时,它使用内部方法来保存/移动/删除使用钩子(Hook)注释关联的图像文件,但我觉得有点像实体本身应该只是相关的 getter 和 setter。
我应该将方法保留在实体中还是将它们移至监听器类?
实体有方法:
- 生成唯一的文件名/路径
- 将图像文件持久保存到磁盘
- 在级联移除时移除图像。
但我不确定我是否喜欢这个存在于我的实体中..
/**
* @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
}
}
最佳答案
这真的取决于用例。引用自 cookbook on how to handle file uploads :
Using lifecycle callbacks is a limited technique that has some drawbacks. If you want to remove the hardcoded DIR reference inside the Document::getUploadRootDir() method, the best way is to start using explicit doctrine listeners. There you will be able to inject kernel parameters such as kernel.root_dir to be able to build absolute paths.
如果您想要两全其美,您可以使用实体监听器。此监听器将仅在该单个实体上触发,而不是监听所有实体:
- http://symfony.com/doc/current/bundles/DoctrineBundle/entity-listeners.html
- http://intelligentbee.com/blog/2015/02/18/symfony2-doctrine-2-entity-listeners/
我还建议查看 Uploadable Doctrine Extension它应该提供您需要的所有功能。
它还提供设置默认上传路径: 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
关于php - 学说 : Symfony2 Listener vs inclass Lifecycle callbacks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30303009/