gpt4 book ai didi

php - Symfony fatal error __construct() 必须是 MyBundle\FileUploader 的实例

转载 作者:行者123 更新时间:2023-12-04 03:12:34 25 4
gpt4 key购买 nike

我确实按照本教程在 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

有问题的 2 个类是 fileuploader 类和 doctrine 文件监听器类。错误出现在 fileListener 中,我认为这是因为我没有在任何地方创建 fileuploader 的对象,但教程没有:

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'

无论如何希望你能有所帮助。谢谢。

最佳答案

在您的 yaml 文件中,您编写 arguments: ['file_uploader']。这会将字符串“file_uploader”传递给 FileListener 的构造函数。您真正想要的是传递由名称“file_uploader”引用的服务。您可以通过在前面添加一个 @ 符号来执行此操作,如下所示:

参数:["@file_uploader"]

关于php - Symfony fatal error __construct() 必须是 MyBundle\FileUploader 的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43850184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com