Associating Files to Doctrine Entities
This chapter describes how to create a file property in a Doctrine entity that you can use to associate a file to an entity, including to store the result of a file upload.
Preparation
To enable this feature, you need to install the package
rekalogika/file-association
:
composer require rekalogika/file-association
Creating a File Property in an Entity
To create a file property in an entity that will be managed by this framework, you need to:
- Create a property that accepts a
FileInterface
. - Add the attribute
#[WithFileAssociation]
to the class. - Add the attribute
#[AsFileAssociation]
to the property.
use Rekalogika\Contracts\File\FileInterface;
use Rekalogika\File\Association\Attribute\WithFileAssociation;
use Rekalogika\File\Association\Attribute\AsFileAssociation;
use Rekalogika\File\File;
#[WithFileAssociation]
class Product
{
/**
* The file property must accept a FileInterface
*/
#[AsFileAssociation]
private ?FileInterface $image = null;
//
// The rest of this class is inconsequential to the framework
//
/**
* This framework reads and writes directly to the properties, even if
* private. Therefore, you are free to have your own business logic in the
* getters and setters.
*/
public function getImage(): FileInterface
{
if (date('m-d') == '04-01') { // if today is april 1st
return new File('shock-image.jpg'); // april fools!
}
return $this->image;
}
public function setImage(?FileInterface $image): self
{
if ($this->status == 'published') {
throw new \Exception("Cannot change a published product's image");
}
$this->image = $image;
return $this;
}
}
Mandatory File
If your business logic necessitates that the file is mandatory to an entity, you
can omit the ?
in the property type hint:
use Rekalogika\Contracts\File\FileInterface;
use Rekalogika\File\Association\Attribute\WithFileAssociation;
use Rekalogika\File\Association\Attribute\AsFileAssociation;
#[WithFileAssociation]
class Product
{
#[AsFileAssociation]
private FileInterface $image;
}
Read more about mandatory files in the chapter Mandatory File.