我有一个控制器和FileUploader :: class。上载器已注入控制器__construct方法。当我在代码中使用这个注入的实例时(请参见下面的内容),每次都得到相同的obj。 我在不使用注入属性的情况下重构了类(请参阅第二部分代码)-它可以工作。但是我想在整个项目中遵循相同的风格。
当它是一个文件上传时,它可以正常工作,但是对于具有循环的多个文件上传解决方案,它不起作用。
class ProposalFileController extends Controller
{
public $fileUploader;
public function __construct(FileUploader $fileUploader)
{
$this->fileUploader = $fileUploader;
}
public function upload(ProposalFileUpload $request)
{
$files = [];
foreach ($request->file('files') as $file)
{
/** !!! Attention here !!!!!!!
In this loop, $this->fileUploader is same obj each time
**/
$files[] = $this->fileUploader->upload($file);
}
return response()
->json([
'data' => $files
]);
}
}
我每次都需要一个新的上载器实例。该类波纹管有效,但我不喜欢这种风格。如何用DI解决方案解决呢?
class ProposalFileController extends Controller
{
public $fileUploader;
public function __construct(FileUploader $fileUploader)
{
$this->fileUploader = $fileUploader;
}
public function upload(ProposalFileUpload $request)
{
$files = [];
foreach ($request->file('files') as $file)
{
$uploader = new FileUploader(new File());
$files[] = $uploader->upload($file);
}
return response()
->json([
'data' => $files
]);
}
}
FileUpload :: class
class FileUploader implements Uploader
{
use UploadHelper;
private $file;
public function __construct(File $file)
{
$this->file = $file;
}
public function upload(UploadedFile $file)
{
$saveName = $this->fileName($file);
/** Save file to s3 */
$storagePath = Storage::disk('s3')->put(...);
/** Set cover_rel - relative path needed for delete file needs */
$this->file->setAttribute('file_rel', $storagePath);
$this->file->save();
return $this->file;
}
}
最后,我得到了具有相同File n次的数组(与循环步骤相同)
答案 0 :(得分:0)
您可以使用下面的app
方法在循环中注入FileUploader实例
$uploader = app(FileUploader::class)