Symfony致命错误__construct()必须是MyBundle\FileUploader的实例

3

我严格按照Symfony上传文件的教程进行操作,但是出现了一个错误,我已经看了大约一个小时了。

完整的错误信息:

FatalThrowableError in FileListener.php line 21:
Type error: Argument 1 passed to MyBundle\FileListener::__construct() 
must be an instance of MyBundle\FileUploader, string given, called in 
/dev/shm/appname/cache/dev/appDevDebugProjectContainer.php on line 830

这两个类分别是文件上传器类和Doctrine文件监听器类。我认为错误出现在文件监听器中,因为我没有在任何地方创建文件上传器的对象,但教程没有提及:

http://symfony.com/doc/current/controller/upload_file.html

文件上传的代码:

namespace MyBundle;

use Symfony\Component\HttpFoundation\File\UploadedFile;

class FileUploader
{
private $targetDir;

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

public function upload(UploadedFile $file)
{
    $fileName = md5(uniqid()).'.'.$file->guessExtension();

    $file->move($this->targetDir, $fileName);

    return $fileName;
}

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

}

文件监听器的代码:

namespace MyBundle;

use Symfony\Component\HttpFoundation\File\UploadedFile;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use MyBundle\Entity\MainMedia;
use MyBundle\FileUploader;

class FileListener
{
private $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 MainMedia) {
        return;
    }

    $file = $entity->getFile();

    // only upload new files
    if (!$file instanceof UploadedFile) {
        return;
    }

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

}

我还设置了YAML服务:
   file_uploader:
  class: MyBundle\FileUploader
  arguments: ['%file_directory%']


  file_listener:
  class: MyBundle\FileListener
  arguments: ['file_uploader']
  tags:
       - { name: doctrine.event_listener, event: prePersist }
       - { name: doctrine.event_listener, event: preUpdate }

并且在配置中的参数用于目录:

  file_directory: '%kernel.root_dir%/../web/uploads'

无论如何希望您能帮忙。谢谢。
1个回答

2
在您的yaml文件中,您写下了arguments: ['file_uploader']。这将字符串“file_uploader”传递给FileListener的构造函数。实际上,您想要传递由名称“file_uploader”引用的服务。您可以通过添加@符号来实现这一点,如下所示:arguments: ["@file_uploader"]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接