Skip to content

Commit 8d56834

Browse files
authored
Update file-upload.md
Added part about serialization when using a file upload with the User entity, which gets serialized by Symfony for the session.
1 parent fea624e commit 8d56834

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

symfony/file-upload.md

+63
Original file line numberDiff line numberDiff line change
@@ -490,3 +490,66 @@ final class UploadedFileDenormalizer implements DenormalizerInterface
490490
If you're not using `autowiring` and `autoconfiguring`, don't forget to register the service and tag it as `serializer.normalizer`.
491491

492492
For resolving the file URL, you can use a custom normalizer, like shown in [the previous example](#resolving-the-file-url).
493+
494+
## Uploading Files on Your User Entity
495+
496+
If you’d like to add file-upload support directly to your `User` entity (rather than a dedicated `MediaObject`), there’s one extra “gotcha” you must handle:
497+
Symfony’s session storage will try to serialize your entire `User` object (including any `File` instance you’ve attached), and `File` is not serializable by default.
498+
499+
To avoid PHP errors like:
500+
```
501+
Serialization of 'Symfony\Component\HttpFoundation\File\File' is not allowed
502+
```
503+
504+
you need to implement both the old `\Serializable` interface **and**, depending on the PHP version, the new `__serialize()` / `__unserialize()` magic methods on your `User`, limiting serialization to just scalar fields (`id`, `email`, `password`, etc.).
505+
Symfony will then happily keep your `User` in the session while VichUploaderBundle handles the file itself.
506+
507+
```php
508+
#[Vich\Uploadable]
509+
#[ORM\Entity]
510+
#[ApiResource(...)]
511+
class User implements UserInterface, PasswordAuthenticatedUserInterface, \Serializable
512+
{
513+
private ?Uuid $id;
514+
private ?string $email;
515+
private ?string $password;
516+
517+
// …
518+
519+
// Legacy Serializable, still used by Symfony SessionStorage
520+
public function serialize(): string
521+
{
522+
return serialize([
523+
(string) $this->id,
524+
$this->email,
525+
$this->password,
526+
]);
527+
}
528+
529+
public function unserialize(string $data): void
530+
{
531+
list(
532+
$this->id,
533+
$this->email,
534+
$this->password,
535+
) = unserialize($data);
536+
}
537+
538+
// PHP 7.4+ Magic Methods
539+
public function __serialize(): array
540+
{
541+
return [
542+
'id' => (string) $this->id,
543+
'email' => $this->email,
544+
'password' => $this->password,
545+
];
546+
}
547+
548+
public function __unserialize(array $data): void
549+
{
550+
$this->id = Uuid::fromString($data['id']);
551+
$this->email = $data['email'];
552+
$this->password = $data['password'];
553+
}
554+
}
555+
```

0 commit comments

Comments
 (0)