Поле blob
Поле blob хранит большие двоичные данные
(binary large object) в базе данных. Оно используется
для сохранения файлов, изображений, аудио и других
нетекстовых данных. В отличие от string и
text, поле blob не имеет ограничения
по кодировке и хранит данные в бинарном виде.
Синтаксис
#[ORMColumn(type: 'blob', options: [])]
Пример
Давайте создадим сущность с полем blob
для хранения файла:
<?php
namespace AppEntity;
use DoctrineORMMapping as ORM;
#[ORMEntity]
#[ORMTable(name: 'files')]
class File
{
#[ORMId]
#[ORMGeneratedValue]
#[ORMColumn(type: 'integer')]
private ?int $id = null;
#[ORMColumn(type: 'string', length: 255)]
private string $name;
#[ORMColumn(type: 'blob')]
private string $content;
public function getId(): ?int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getContent(): string
{
return $this->content;
}
public function setContent(string $content): self
{
$this->content = $content;
return $this;
}
}
?>
Пример
Давайте сохраним бинарные данные в поле blob:
<?php
namespace AppController;
use AppEntityFile;
use DoctrineORMEntityManagerInterface;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;
class FileController extends AbstractController
{
#[Route('/file/save', name: 'file_save')]
public function save(EntityManagerInterface $em): Response
{
$file = new File();
$file->setName('article');
$file->setContent(file_get_contents('/path/to/file'));
$em->persist($file);
$em->flush();
return new Response('saved');
}
}
?>
Результат выполнения кода:
"saved"
Пример
Давайте прочитаем бинарные данные из поля blob
и вернём их в ответе:
<?php
namespace AppController;
use AppEntityFile;
use DoctrineORMEntityManagerInterface;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;
class FileController extends AbstractController
{
#[Route('/file/{id}', name: 'file_show')]
public function show(int $id, EntityManagerInterface $em): Response
{
$file = $em->getRepository(File::class)->find($id);
if (!$file) {
return new Response('not found', 404);
}
return new Response($file->getContent());
}
}
?>
Результат выполнения кода для адреса /file/1:
"binary content"