![]() |
VOOZH | about |
The conference dedicated to API Platform and its ecosystem
The following options can be used in the configuration file.
Namespaces of generated PHP classes can be set globally, respectively for entities, enumerations and interfaces (if used with Doctrine Resolve Target Entity Listener option).
Example:
namespaces:entity:"App\ECommerce\Entity"enum:"App\ECommerce\Enum"interface:"App\ECommerce\Model"Namespaces can also be specified for a specific type. It will take precedence over any globally configured namespace.
Example:
types:Thing:namespaces:class:"App\Common\Entity"# Namespace for the Thing entity (works for enumerations too)interface:"App\Schema\Model"# Namespace of the related interfaceRDF allows a property to have several types (ranges). However, the generator allows only one type
per property. If not configured, it will use the first defined type. The range option is useful to
set the type of a given property. It can also be used to force a type (even if not in the RDF
vocabulary definition).
Example:
types:Brand:properties:logo:{range:"ImageObject"}# Force the range of the logo property to ImageObject (can also be a URL according to Schema.org)PostalAddress:properties:addressCountry:{range:"Text"}# Force the type to Text instead of Country. It will be converted to the PHP string type.The cardinality of a property is automatically guessed. The cardinality option allows to override
the guessed value. Supported cardinalities are:
(0..1): scalar, not required(0..*): array, not required(1..1): scalar, required(1..*): array, required(*..0)(*..1)(*..*)Cardinalities are enforced by the class generator, the Doctrine ORM generator and the Symfony validation generator.
Example:
types:Product:properties:sku:cardinality:"(0..1)"When a cardinality has not been guessed, a default cardinality will be used instead.
By default, the cardinality (1..1) is used, but you can change it like this:
relations:defaultCardinality:"(1..*)"You can add any custom attribute you want, or you can modify the arguments of any generated attribute, for a property, a class or even a whole vocabulary!
For instance, if you want to change the join table name and add security for a specific relation:
types:Organization:properties:contactPoint:attributes:ORM\JoinTable:{name:organization_contactPoint }# Instead of organization_contact_point by defaultApiProperty:{security:"is_granted('ROLE_ADMIN')"}To add a custom attribute, you also need to add it in the uses option:
uses:App\Attributes\MyAttribute:~types:Book:attributes:- ApiResource:{routePrefix:"/library"}# Add a route prefix for this resource- MyAttribute:~# Note the optional usage of a hyphen list: it allows to preserve the order of attributesOverride the guessed class hierarchy of a given type with this option.
Example:
types:ImageObject:parent:Thing# Force the parent to be Thing instead of CreativeWork > MediaObjectproperties:~Drug:parent:~# Enable the class hierarchy for this typeForce a class to be (or to not be) abstract. By default, it will be guessed, depending on the
class hierarchy and if the class is used in a relation.
Example:
types:Person:abstract:trueAPI Platform operations can be added this way:
types:Person:operations:Get:~GetCollection:routeName:get_person_collectionForce a property to be (or to not be) nullable.
By default, this option is null: the cardinality will be used to determine the nullability. If no
cardinality is found, it will be true.
Example:
Person:properties:name:{nullable:false}The #[Assert\NotNull] constraint is automatically added.
<?php
/**
* The name of the item.
*/
#[ORM\Column]
#[Assert\NotNull]
private string $name;Force a property to be (or to not be) unique.
By default, this option is false.
Example:
Person:properties:email:{unique:true}Output:
<?php
// api/src/Entity/Person.php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Doctrine\ORM\Mapping as ORM;
/**
* A person (alive, dead, undead, or fictional).
*
* @see https://schema.org/Person
*/
#[ORM\Entity]
#[ApiResource(types: ['https://schema.org/Person'])]
#[UniqueEntity('email')]
class Person
{
/**
* Email address.
*
* @see https://schema.org/email
*/
#[ORM\Column]
#[Assert\Email]
private string $email;
// ...
}A property can be marked read-only with the following configuration:
Person:properties:email:{writable:false}In such case, no mutator method will be generated.
A property can be marked write-only with the following configuration:
Person:properties:email:{readable:false}In this case, no getter method will be generated.
Force an embeddable class to be embedded.
Example:
QuantitativeValue:embeddable:trueProduct:properties:weight:{range:"QuantitativeValue", embedded:true}Output:
<?php
// api/src/Entity/Product.php
namespace App\Entity;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use Doctrine\ORM\Mapping as ORM;
/**
* Any offered product or service.
*
* @see https://schema.org/Product Documentation on Schema.org
*/
#[ORM\Entity]
#[ApiResource(types: ['https://schema.org/Product'])]
#[UniqueEntity('gtin13s')]
class Product
{
/**
* The weight of the product or person.
*
* @see https://schema.org/weight
*/
#[ORM\Embedded(class: QuantitativeValue::class)]
#[ApiProperty(iri: 'https://schema.org/weight')]
private ?QuantitativeValue $weight = null;
// ...
}It’s possible to skip the generation of accessor methods. This is particularly useful combined with
the visibility: public option.
To skip the generation of accessor methods, use the following config:
accessorMethods:falseIf you want to generate fluent mutator methods, like this:
public function setName(?string $name): self
{
$this->name = $name;
return $this;
}Use the following config:
fluentMutatorMethods:trueid GeneratorBy default, the generator adds a property called id not provided by Schema.org. This is useful
when generating an entity for use with an ORM or an ODM but not when generating DTOs. This behavior
can be disabled with the following setting:
id:generate:falseIt’s also possible to let the DBMS generate UUIDs instead of auto-incremented integers:
id:generationStrategy:uuidTo manually set a UUID instead of letting the DBMS generate it, use the following config:
id:generationStrategy:uuidwritable:trueWith this configuration option, an $id property of type string and the corresponding getters and
setters will be generated, but the DBMS will not generate anything. The ID must be set manually.
id:generationStrategy:noneBy default, the generator uses classes provided by the Doctrine Collections library to store collections of entities. This is useful (and required) when using Doctrine ORM or Doctrine MongoDB ODM. This behavior can be disabled (to fall back to standard arrays) with the following setting:
doctrine:useCollection:falseGenerated fields have a private visibility and are exposed through getters and setters. The
default visibility can be changed with the fieldVisibility option.
Example:
fieldVisibility:"protected"Assert\Type AttributesIt’s possible to automatically generate Symfony validator’s #[Assert\Type] attributes using the
following config:
validator:assertType:trueThe generator is able to handle inheritance in a smart way:
#[InheritanceType] (configurable, see below), #[DiscriminatorColumn]
(#[DiscriminatorField] for ODM) and #[DiscriminatorMap]. The discriminator map will be filled
with all possible values.#[MappedSuperclass]). If this mapped superclass defines relations and is used by multiple
children, the generator will add #[AssociationOverride] attributes to them (see the
related Doctrine documentation),
thanks to the special DoctrineOrmAssociationOverrideAttributeGenerator.#[Entity] (or #[Document] for ODM) attribute is used.If this behaviour does not suit you, the inheritance attribute can be forced in the following way:
doctrine:inheritanceType: SINGLE_TABLE # Default:JOINEDinheritanceAttributes:CustomInheritanceAttribute:[]ResolveTargetEntityListener
is a feature of Doctrine to keep modules independent. It allows to specify interfaces and abstract
classes in relation mappings.
If you set the option useInterface to true, the generator will generate an interface corresponding
to each generated entity and will use them in relation mappings.
To let the schema generator generate the mapping file usable with Symfony, add the following to your config file:
doctrine:resolveTargetEntityConfigPath:path/to/doctrine.xmlThe default mapping file format is XML, but you can change it to YAML with the following option:
doctrine:resolveTargetEntityConfigPath:path/to/doctrine.yamlresolveTargetEntityConfigType:YAML# Supports XML & YAMLBy default, the mapping file is in XML. If you want to have a YAML file, add the following:
doctrine:resolveTargetEntityConfigPath:path/to/doctrine.yamlresolveTargetEntityConfigType:yamlThe generator can use your own schema definitions. They must be written in RDF/XML and follow the format of the Schema.org’s definition. This is useful to document your Schema.org extensions and use them to generate the PHP data model of your application.
Example:
vocabularies:- https://github.com/schemaorg/schemaorg/raw/main/data/releases/13.0/schemaorg-current-https.rdf- http://example.com/data/myschema.rdf# Additional typesYou can also use any other vocabulary. Check the Linked Open Vocabularies to find one fitting your needs.
For instance, to generate a data model from the Video Game Ontology, use the following config file:
vocabularies:- http://vocab.linkeddata.es/vgo/GameOntologyv3.owl# The URL of the vocabulary definitiontypes:Session:vocabularyNamespace:http://purl.org/net/VideoGameOntology## ...If you use multiple vocabularies, and you need to generate all types for some ones, only generate types when they are used for some others and exclude some types, you can do so with this kind of configuration:
vocabularies:# Schema.org classes will only be generated when one of its type is used in the other vocabularies.- {uri:"https://schema.org/version/latest/schemaorg-current-https.rdf",format:null,allTypes:false,}- http://vocab.linkeddata.es/vgo/GameOntologyv3.owlallTypes:true# Generate all types by default for vocabulariesresolveTypes:true# Resolve types in other vocabulariestypes:GameEvent:exclude:true# Exclude the GameEvent typeIf the checkIsGoodRelations option is set to true, the generator will emit a warning if an
encountered property is not par of the
GoodRelations schema.
This is useful when generating e-commerce data models.
Add a @author PHPDoc annotation to class DocBlock.
Example:
author:"Kévin Dunglas <[email protected]>"Prepend all generated PHP files with a custom comment.
Example:
header:| /*
* This file is part of the Ecommerce package.
*
* (c) Kévin Dunglas <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/By default, all generators except DoctrineMongoDBAttributeGenerator are enabled. You can specify
the list of generators to use with the annotationGenerators and attributeGenerators option.
Example (enabling only the PHPDoc generator):
annotationGenerators:- ApiPlatform\SchemaGenerator\AnnotationGenerator\PhpDocAnnotationGeneratorattributeGenerators:[]You can write your own generators by implementing the AnnotationGeneratorInterface or
AttributeGeneratorInterface. The AbstractAnnotationGenerator or AbstractAttributeGenerator
provides helper methods useful when creating your own generators.
Enabling a custom attribute generator and the PHPDoc generator:
annotationGenerators:- ApiPlatform\SchemaGenerator\AnnotationGenerator\PhpDocAnnotationGeneratorattributeGenerators- Acme\Generators\MyGeneratoropenApi:file:null# RDF vocabulariesvocabularies:# Prototypeuri:# RDF vocabulary to useuri: ~ # Example:'https://schema.org/version/latest/schemaorg-current-https.rdf'# RDF vocabulary formatformat: null # Example:rdfxml# Generate all types for this vocabulary, even if an explicit configuration exists. If allTypes is enabled globally, it can be disabled for this particular vocabularyallTypes:null# Attributes (merged with generated attributes)attributes:[]# Namespace of the vocabulary to importvocabularyNamespace:"https://schema.org/"# Example: 'http://www.w3.org/ns/activitystreams#'# Relations configurationrelations:# OWL relation URIs containing cardinality information in the GoodRelations formaturis: # Example:'https://archive.org/services/purl/goodrelations/v1.owl'# Default:- https://archive.org/services/purl/goodrelations/v1.owl# The default cardinality to use when it cannot be extracteddefaultCardinality:(1..1)# One of "(0..1)"; "(0..*)"; "(1..1)"; "(1..*)"; "(*..0)"; "(*..1)"; "(*..*)"# Debug modedebug:false# Use old API Platform attributes (API Platform < 2.7)apiPlatformOldAttributes:false# IDs configurationid:# Automatically add an ID field to entitiesgenerate:true# The ID generation strategy to use ("none" to not let the database generate IDs).generationStrategy:auto# One of "auto"; "none"; "uuid"; "mongoid"# Is the ID writable? Only applicable if "generationStrategy" is "uuid".writable:false# Generate interfaces and use Doctrine's Resolve Target Entity featureuseInterface:false# Emit a warning if a property is not derived from GoodRelationscheckIsGoodRelations:false# A license or any text to use as header of generated filesheader: null # Example:'// (c) Kévin Dunglas <[email protected]>'# PHP namespacesnamespaces:# The global namespace's prefixprefix: null # Example:App\# The namespace of the generated entitiesentity: App\Entity # Example:App\Entity# The namespace of the generated enumerationsenum: App\Enum # Example:App\Enum# The namespace of the generated interfacesinterface: App\Model # Example:App\Model# Custom uses (for instance if you use a custom attribute)uses:# Prototypename:# Name of this usename: ~ # Example:App\Attributes\MyAttribute# The alias to use for this usealias:null# Doctrinedoctrine:# Use Doctrine's ArrayCollection instead of standard arraysuseCollection:true# The Resolve Target Entity Listener config file pathresolveTargetEntityConfigPath:null# The Resolve Target Entity Listener config file typeresolveTargetEntityConfigType:XML# One of "XML"; "yaml"# Doctrine inheritance attributes (if set, no other attributes are generated)inheritanceAttributes:[]# The inheritance type to use when an entity is referenced by another and has childinheritanceType:JOINED# One of "JOINED"; "SINGLE_TABLE"; "SINGLE_COLLECTION"; "TABLE_PER_CLASS"; "COLLECTION_PER_CLASS"; "NONE"# Maximum length of any given database identifier, like tables or column namesmaxIdentifierLength:63# Symfony Validator Componentvalidator:# Generate @Assert\Type annotationassertType:false# The value of the phpDoc's @author annotationauthor: false # Example:'Kévin Dunglas <[email protected]>'# Visibility of entities fieldsfieldVisibility:private# One of "private"; "protected"; "public"# Set this flag to false to not generate getter, setter, adder and remover methodsaccessorMethods:true# Set this flag to true to generate fluent setter, adder and remover methodsfluentMutatorMethods:falserangeMapping:# Prototypename:~# Generate all types, even if an explicit configuration existsallTypes:false# If a type is present in a vocabulary but not explicitly imported (types) or if the vocabulary is not totally imported (allTypes), it will be generatedresolveTypes:false# Types to import from the vocabularytypes:# Prototypeid:# Exclude this type, even if "allTypes" is set to true"exclude:false# Namespace of the vocabulary of this type (defaults to the global "vocabularyNamespace" entry)vocabularyNamespace: null # Example:'http://www.w3.org/ns/activitystreams#'# Is the class abstract? (null to guess)abstract:null# Is the class embeddable?embeddable:false# Type namespacesnamespaces:# The namespace for the generated class (override any other defined namespace)class:null# The namespace for the generated interface (override any other defined namespace)interface:null# Attributes (merged with generated attributes)attributes:[]# The parent class, set to false for a top level classparent:false# If declaring a custom class, this will be the class from which properties type will be guessedguessFrom:Thing# Operations for the classoperations:[]# Import all existing propertiesallProperties:false# Properties of this type to useproperties:# Prototypeid:# Exclude this property, even if "allProperties" is set to true"exclude:false# The property rangerange: null # Example:Offercardinality:unknown# One of "(0..1)"; "(0..*)"; "(1..1)"; "(1..*)"; "(*..0)"; "(*..1)"; "(*..*)"; "unknown"# Symfony Serialization Groupsgroups:[]# The doctrine mapped by attributemappedBy: null # Example:partOfSeason# The doctrine inversed by attributeinversedBy: null # Example:episodes# Is the property readable?readable:true# Is the property writable?writable:true# Is the property nullable? (if null, cardinality will be used: will be true if no cardinality found)nullable:null# Is the property required?required:true# The property uniqueunique:false# Is the property embedded?embedded:false# Attributes (merged with generated attributes)attributes:[]# Annotation generators to useannotationGenerators:# Default:- ApiPlatform\SchemaGenerator\AnnotationGenerator\PhpDocAnnotationGenerator# Attribute generators to useattributeGenerators:# Defaults:- ApiPlatform\SchemaGenerator\AttributeGenerator\DoctrineOrmAttributeGenerator- ApiPlatform\SchemaGenerator\AttributeGenerator\DoctrineOrmAssociationOverrideAttributeGenerator- ApiPlatform\SchemaGenerator\AttributeGenerator\ApiPlatformCoreAttributeGenerator- ApiPlatform\SchemaGenerator\AttributeGenerator\ConstraintAttributeGenerator- ApiPlatform\SchemaGenerator\AttributeGenerator\ConfigurationAttributeGenerator# Directories for custom generator twig templatesgeneratorTemplates:[]You can also help us improve the documentation of this page.
Using an AI coding agent? See the documentation index for LLMs at /docs/llms.txt.
Made with love by
Les-Tilleuls.coop can help you design and develop your APIs and web projects, and train your teams in API Platform, Symfony, Next.js, Kubernetes and a wide range of other technologies.
Learn more