php - 学说 : Symfony2 Listener vs inclass Lifecycle callbacks

标签 php symfony doctrine-orm

我一直在处理一个图像实体,当持久化时,它使用内部方法来保存/移动/删除使用钩子(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.

如果您想要两全其美,您可以使用实体监听器。此监听器将仅在该单个实体上触发,而不是监听所有实体:

我还建议查看 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/

相关文章:

php - MySQL SELECT 在 PDO 中带有子查询以获取每月统计信息

php - 获取匿名函数的字符串表示

php - Facebook登录卡住空白页

symfony - 在学说实体保存期间更新/插入缓存条目

php - Symfony Controller 魔术方法?

php - "Class XXX is not a valid entity or mapped super class"在文件系统中移动类后

php - 无法将值插入到 OneToOne 关系中的 Doctrine 2 中的映射列

php - 过滤后,检查过滤后数组是否不为空或是否具有所有原始值;像 Javascript 的 some() 和 every()

php - 在坚持 Symfony2 形式和学说后重定向