通过Symfony2

时间:2016-06-22 16:47:50

标签: php symfony

我已经成功创建了一个服务和一个监听器来自动保存我的Post实体中的文件。

一切正常,但我需要在Post实体中添加另一个字段:'photo'。使用尽可能多的以下代码来实现这一目标的正确方法是什么?我试图将一些参数传递给监听器,但我可以让它工作......

宣传册应保存在:网络/上传/宣传册以及网络/上传/照片下的照片。

用户必须提供宣传册和照片。

感谢您的帮助。

services.yml:

# brochure uploader service
app.brochure_uploader:
    class: AppBundle\Utils\FileUploader
    arguments: [ '%brochures_directory%' ]

# uploaded files for Post entity
app.doctrine_brochure_listener:
    class: AppBundle\EventListener\BrochureUploadListener
    arguments: [ '@app.brochure_uploader' ]
    tags:
        - { name: doctrine.event_listener, event: prePersist }
        - { name: doctrine.event_listener, event: preUpdate }     

的Utils / FileUploader.php:

namespace AppBundle\Utils;

use Symfony\Component\HttpFoundation\File\UploadedFile;

class FileUploader
{
    private $targetDir;

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

    public function upload(UploadedFile $file = null)
    {
        $fileName = md5(uniqid()).'.'.$file->guessExtension();
        $file->move($this->targetDir, $fileName);

        return $fileName;
    }

    public function getTargetDir() {
        return $this->targetDir;
    }
}

EventLister / BrochureUploadListener.php:

类BrochureUploadListener {     私人$ uploader;

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

public function prePersist(LifecycleEventArgs $args)
{
    $entity = $args->getEntity();
    $this->uploadFile($entity);
}

public function preUpdate(PreUpdateEventArgs $args)
{
    $entity = $args->getEntity();
    $this->uploadFile($entity);
}

private function uploadFile($entity)
{
    if (!$entity instanceof Post) {
        return;
    }

    $file = $entity->getBrochure();

    if (!$file instanceof UploadedFile) {
        return;
    }

    $fileName = $this->uploader->upload($file);
    $entity->setBrochure($fileName);
}

}

表单/ PostType.php:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
       [...]
        ->add('brochure', 'Symfony\Component\Form\Extension\Core\Type\FileType', array(
            'label' => 'Brochure (PDF file)',
            'data_class' => null,
        ))
       [...]
    ;
}

实体/ post.php中

/**
 * @ORM\Column(type="string")
 *
 * @Assert\File(mimeTypes={ "application/pdf" })
 */
private $brochure;  

1 个答案:

答案 0 :(得分:0)

不要重新发明轮子。 使用VichUploaderBundle(也是官方Symfony文档建议)并且开心