In this article we assume that you are familiar with The YAML Format and Configuration File Principles.
The purpose of schema files is to allow you to manage your model definitions directly from a YAML file rather then editing php code. The YAML schema file is parsed and used to generate all your model definitions/classes. This makes Doctrine model definitions much more portable.
Doctrine 1.2
# Global parameters detect_relations: <true | false> connection: connection_name package: package_name inheritance: inheritance_information actAs: behavior_information options: options_information attributes: attributes_information # Model definition model_name: connection: connection_name tableName: table_name className: class_name abstract: <true | false> listeners: [ListenerClass1, ListenerClass2, ...] package: package_name package_custom_path: /path/to/generate/package inheritance: extends: model_to_extend type: <simple | concrete | column_aggregation> keyField: key_field_name keyValue: key_field_value columns: column_name: name: column_name type: <string | char | boolean | integer | float | decimal | blob | clob | enum | timestamp> length: column_length scale: column_scale values: ['enum_value1', 'enum_value2', ...] default: default_value unsigned: <true | false> unique: <true | false> primary: <true | false> autoincrement: <true | false> comment: column_comment notnull: <true | false> email: <true | false> notblank: <true | false> nospace: <true | false> past: <true | false> future: <true | false> minlength: length_value country: <true | false> ip: <true | false> htmlcolor: <true | false> range: [start_value, end_value] regexp: regexp_value creditcard: <true | false> date: <true | false> usstate: <true | false> relations: relation_name: local: local_column_name foreign: foreign_column_name type: <one | many> class: class_name refClass: ref_class foreignType: <one | many> alias: alias foreignAlias: foreign_alias owningSide: <true | false> equal: <true | false> foreignKeyName: foreign_key_name onDelete: <CASCADE | SET NULL | NO ACTION | RESTRICT | SET DEFAULT> onUpdate: <CASCADE | SET NULL | NO ACTION | RESTRICT | SET DEFAULT> cascade: [delete] indexes: index_name: type: <unique | fulltext | gist | gin> fields: [fieldname1, fieldname2, ...] checks: check_name: check_condition actAs: Versionable: version: {name: field_name, type: field_type, length: field_length} auditLog: <true | false> Timestampable: created: name: column_name type: column_type format: date_format disabled: <true | false> options: {notnull: <true | false>} updated: name: column_name type: column_type format: date_format onInsert: <true | false> disabled: <true | false> options: {notnull: <true | false>} Sluggable: name: slug_column_name alias: slug_column_alias type: slug_column_type length: slug_column_length unique: <true | false> fields: [fieldname1, fieldname2, ...] uniqueIndex: <true | false> uniqueBy: [fieldname1, fieldname2, ...] indexName: index_name canUpdate: <true | false> builder: [class, method] I18n: fields: [fieldname1, fieldname2, ...] tableName: translation_table_name i18nField: lang_column_name type: lang_column_type length: lang_column_length NestedSet: rootColumnName: root_column_name hasManyRoots: <true | false> Searchable: fields: [fieldname1, fieldname2, ...] batchUpdates: <true | false> Geographical: latitude: name: column_name type: column_type longitude: name: column_name type: column_type SoftDelete: name: column_name type: column_type options: type: <INNODB | MyISAM> collate: collation_name charset: charset_name orderBy: column1 <ASC | DESC>, column2 <ASC | DESC>, ... symfony: filter: <true | false> form: <true | false> attributes: export: <all | tables | none> validate: <all | lengths | types | none> hydrate_overwrite: <true | false> query_class: class_name collection_class: class_name coll_key: column_name
Doctrine schemas allow you to specify certain parameters that will apply to all of the models defined in the schema file. Below you can find list of global parameters you can set for schema files.
Specifies whether or not to try and detect foreign key relations. This option will attempt to guess relationships based on column names. For example, if you have a User model with a contact_id and a class with the name Contact exists, it will automatically create the relationships between the two. Possible values: <true | false> Default: false
Name of connection to bind the models to. This parameter binds models to a specific connection which is defined in databases.yml file.
Package to put the models in. This parameter will generate the models in to sub-folders. With large schema files this will allow you to better organize your schemas in to folders. You can specify more sub folders by doing «package: Folder.Subfolder» and the models would be generated in Folder/Subfolder.
Array of inheritance information for models. For details see the «inheritance» parameter defined in the model scope.
Specifies an array of behaviors for the models to act as. For details see the «actAs» parameter defined in the model scope.
Specifies an array of global tables options for the models. When Doctrine creates your tables from your models, these options will be set on the create table statement. For details see the «options» parameter defined in the model scope.
Specifies the array of attributes for models. Doctrine offers the ability to set attributes for your generated models directly in your schema files similar to how you would if you were manually writing your Doctrine_Record child classes. For details see the «attributes» parameter defined in the model scope.
This is the root section of the model definition and specifies model name.
Name of connection to bind the model to. This parameter binds model to a specific connection which is defined in databases.yml file.
Specifies a database table name. If this option is not defined, then table name is generated using model name.
Specifies a model PHP class name. If this option is not defined, then class name is generated using model name.
Specifies whether to make model class as abstract. If this option is set to true, then the abstract modifier is added to the declaration of the model class. Possible values: <true | false> Default: false
Specifies an array of listener classes which will be attached to a model.
Specifies the package to put the models in. This parameter will generate the model in to sub-folders. With large schema files this will allow you to better organize your schemas in to folders. You can specify more sub folders by doing «package: Folder.Subfolder» and the models would be generated in Folder/Subfolder.
Specifies a custom path to generate the package files to.
Specifies an array of inheritance information for models.
Specifies model class to extend.
Doctrine supports three types of inheritance strategies which can be mixed together:
Possible values: <simple | concrete | column_aggregation>
This option is used together with column aggregation inheritance and specifies the name of the column, which stores inherited model type value defined in keyValue option. Doctrine automatically adds this column to the create statement of the database table so you do not need to define it in the columns section.
This option is used together with column aggregation inheritance and specifies tha value that identifies the inherited model type. This value is stored in the database column specified by the keyField option.
Specifies an array of column information for models.
The name of this section defines the name for the column in database table and in generated model. This name can be overwritten in tne name attribute.
Defines the name for the column in database and in generated model. If you want the ability alias a column name as something other than the column name in the database this is easy to accomplish by using the syntax «column_name as field_name» in the name of a column. Eg.:
Model: columns: login: name: //login as username// password: ...
The above example would allow you to access the column named login from the alias username..
Specifies the data type of the column. Possible values: <string | char | boolean | integer | float | decimal | blob | clob | enum | timestamp>
An integer value that specifies the column length. Some column types depend not only the given portable type but also on the given length. For example type string with length 1000 will be translated into native type TEXT on mysql.
The length is different depending on the type of column you are using:
The scale for a decimal column.
This option is used together with [i]enum[\i] column type and specifies an array of values for the possible enum values.
Specifies the default value for the column. This value is attached to every newly created Record and when Doctrine creates your database tables it includes the default value in the create table statement.
Checks if given integer value is unsigned. Default: false
Specifies whether the column is a unique key. Unique constraint creates unique index for the column and ensure that the data contained in a column or a group of columns is unique with respect to all the rows in the table. Possible values: <true | false> Default: false
Specifies whether the column is a primary key. Possible values: <true | false> Default: false
Specifies whether a column is a special identity column in the database that generates a value on insertion of a row. Possible values: <true | false> Default: false
Specifies a column comment which is added to the create table statement.
Ensures the 'not null' constraint in both application and database level. A not-null constraint simply specifies that a column must not assume the null value. A not-null constraint is always written as a column constraint. Possible values: <true | false> Default: false
Checks if value is valid email. The e-mail validator simply validates that the inputted value is indeed a valid e-mail address and that the MX records for the address domain resolve as a valid e-mail address. Possible values: <true | false> Default: false
Checks if value is not blank. The not blank validator is similar to the not null validator except that it will fail on empty strings or strings with white space. Possible values: <true | false> Default: false
Checks that the value doesn't contain any spaces. Possible values: <true | false> Default: false
The past validator checks if the given value is a valid date in the past. Possible values: <true | false> Default: false
The future validator checks if the given value is a valid date in the future. Possible values: <true | false> Default: false
Checks that the value string length is equal or greater than the specified minimum length.
Checks if value is a valid country code. Possible values: <true | false> Default: false
Checks if value is valid IP (internet protocol) address. Possible values: <true | false> Default: false
Checks that the given value is a valid html hex color. Possible values: <true | false> Default: false
Checks if value is within given range of numbers. Used with numeric fields. You can use the range validator to validate max and min values by omitting either one of the 0 or 1 keys of the range array. Below is an example:
User: columns: ... age: type: integer(3) range: 1: 100
Checks if value matches a given regexp.
Checks whether the string is a well formated credit card number. Possible values: <true | false> Default: false
Checks if given value is a valid date. Possible values: <true | false> Default: false
Checks if given string is a valid US state code. Possible values: <true | false> Default: false
A hefty part of designing a relational database is dividing the data elements into related tables. Once you're ready to start working with the data, you rely on relationships between the tables to pull the data together in meaningful ways. Relationships between the tables are required to reduce data redundancy and to improve efficiency. When specifying relationships it is only necessary to specify the relationship on the end where the foreign key exists. When the schema file is parsed, it reflects the relationship and builds the opposite end automatically. If you specify the other end of the relationship manually, the auto generation will have no effect.
Specifies the name of the relation. Usualy relation name is the name of the model class this relation is associated to. Otherwise the model class must be specified in the class attribute.
The local field of the relation. Local field is the linked field in the defining class.
The foreign field of the relation. Foreign field is the linked field in the linked class.
Specifies the cardinality 'one' or 'many' of the relation. Possible values: <one | many>
Specifies the associated model class name.
The name of the association class. This is only needed for many-to-many associations.
Specifies the cardinality 'one' or 'many' of the relation in the foreign class. Possible values: <one | many>
Specifies the relation alias which is used in the model class to refer to associated foreign record collection.
Specifies the relation alias which is used in the foreign model class to refer to associated record collection.
Set this attribute to true to indicate the owning side of the relation. The owning side is the side that owns the foreign key. There can only be one owning side in an association between two classes. Note that this option is required if Doctrine can't guess the owning side or it's guess is wrong. An example where this is the case is when both 'local' and 'foreign' are part of the identifier (primary key). It never hurts to specify the owning side in this way.
Specifies equal nest relation. Used for expressing relations where a class references to itself and the columns within the reference class are equal. This means that when fetching related records it doesn't matter which column in the reference class has the primary key value of the main class. Possible values: <true | false> Default: false
When you define a relationship, Doctrine will try to create a foreign key name for you. Sometimes though, this name may not be something you want so you can customize the name to use with this option.
The onDelete integrity action that is applied on the foreign key constraint when the tables are created by Doctrine.
The integrity constraints listed above are case sensitive and must be in upper case when being defined in your schema. Possible values: <CASCADE | SET NULL | NO ACTION | RESTRICT | SET DEFAULT>
The onUpdate integrity action that is applied on the foreign key constraint when the tables are created by Doctrine.
The integrity constraints listed above are case sensitive and must be in upper case when being defined in your schema. Possible values: <CASCADE | SET NULL | NO ACTION | RESTRICT | SET DEFAULT>
This option is used to specify the operations that are cascaded to the related objects on the application-level. Note that the only currently supported value is delete.
Indexes are used to find rows with specific column values quickly. Without an index, the database must begin with the first row and then read through the entire table to find the relevant rows.
Defines index name. This name is used to generate index name in the database.
Specifies index type. The fulltext index is only supported by MySQL database MyISAM engine. The GiST index is supported by PostgreSQL. Possible values: <unique | fulltext | gist | gin>
Specifies an array of indexed fields.
You can create any kind of CHECK constraints by defining them in this section. Some databases don't support CHECK constraints. When this is the case Doctrine simply skips the creation of check constraints.
Specifies the name of the check constraint and the check condition. Check condition can be any valid boolean expression, eg.:
Product: ... checks: price_check: price > discounted_price
This parameter specifies the array of behaviors for the models to act as. When referring to behaviors we refer to class packages that use templates, generators and listeners. These templates are used for adding common definitions and options to record classes. Listeners are used to add Doctrine event based actions.
This template adds version control for table records. Versionable behavior adds an XxxVersion table to store your Xxx model object versions as either only version numbers or version numbers along with ALL column data - to see object data changes through time. If you want this behavior to be configured for you automatically, enter tilde ('~') as a value for this option. Below is an example:
Model: ... actAs: Versionable: ~
Defines attributes for version column:
Default: {name: version, type: integer, length: 8}
The auditLog option can be used to turn off the audit log history. This is when you want to maintain a version number but not maintain the data at each version. When auditLog option is set to true, Doctrine creates additional table named {%model_name%_version} which has column structure equal to model column structure and a reference to actual model record. This table is used to maintain the data at each version. Everytime a model object is deleted / updated the previous version is stored into model versions table. Possible values: <true | false> Default: true
The Timestampable behavior will automatically add a created_at and updated_at columns and automatically set the values when a record is inserted and updated. If you want this behavior to be configured for you automatically, enter tilde ('~') as a value for this option. Below is an example:
Model: ... actAs: Timestampable: ~
Specifies the array of attributes for created_at column.
The name of the created_at column. Default: created_at
The type of the created_at column. Default: timestamp
The format of the timestamp if you don't use the timestamp column type. The date is built using PHP's date() function. Default: Y-m-d H:i:s
Specifies whether or not to disable created_at date. When this option is set to true, the created_at column will not be added to the data model. Possible values: <true | false> Default: false
Specifies the additional options for created_at column. Default: {notnull: true}
Specifies the array of attributes for updated_at column.
The name of the updated_at column. Default: updated_at
The type of the updated_at column. Default: timestamp
The format of the timestamp if you don't use the timestamp column type. The date is built using PHP's date() function. Default: Y-m-d H:i:s
Specifies whether or not to add updated_at timestamp when a new record is inserted to database. Possible values: <true | false> Default: true
Specifies whether or not to disable updated_at date. When this option is set to true, the updated_at column will not be added to the data model. Possible values: <true | false> Default: false
Specifies the additional options for updated_at column. Default: {notnull: true}
The Sluggable behavior will automatically add a column to your model for storing a unique human readable identifier that can be created from columns like title, subject, etc. These values can be used for search engine friendly urls.
The name of the slug column. Default: slug
The alias of the slug column.
The type of the slug column. Default: string
The length of the slug column. Default: 255
This flag will enforce that the slug created is unique. If it is not unique an auto incremented integer will be appended to the slug before saving to database. Possible values: <true | false> Default: true
The fields that are used to build slug value.
Specifies whether or not to create a unique index for slug. This option has effect when the unique option is also set to true. Possible values: <true | false> Default: true
The fields that make determine a unique slug. These fields together with the slug column are included into the unique index.
The name of the index to create.
Specifies whether or not the slug can be updated. The canUpdate flag will allow the users to manually set the slug value to be used when building the url friendly slug. Possible values: <true | false> Default: false
The Class::method() used to build the slug. Default: [Doctrine_Inflector, urlize]
I18n is a behavior for Doctrine that provides internationalization support for record classes. Essential when developing a multi-language project.
The fields to internationalize.
Table name to use for translations table. Default: %TABLE%_translation
The name of language column. Default: lang
The type of language column. Default: string
The length of the language column. Default: 2
This behavior allows you to turn your models in to a nested set tree structure where the entire tree structure can be retrieved in one efficient query. It also provides a nice interface for manipulating the data in your trees. If you want this behavior to be configured for you automatically, enter tilde ('~') as a value for this option. Below is an example:
Model: ... actAs: NestedSet: ~
The rootColumnName is the column used to differentiate between trees. When you create a new root node you have the option to set the root_id manually, otherwise Doctrine will assign a value for you. Default: root_id
Specifies whether to allow your table to have multiple root nodes, and therefore multiple trees within the same table. Possible values: <true | false> Default: false
The Searchable behavior is a fulltext indexing and searching tool. It can be used for indexing and searching both database and files.
Specifies array of searchable fields.
If you don't have batch updates enabled then the index will be automatically updated for you when you insert or update searchable records. If you do have batch updates enabled then you can perform the batch updates by invoking the batchUpdateIndex() method in the table class. Possible values: <true | false> Default: false
The Geographical behavior can be used with any data record for determining the number of miles or kilometers between 2 records. Geographical behavior automatically adds the latitude and longitude columns to the records used for calculating distance between two records. If you want this behavior to be configured for you automatically, enter tilde ('~') as a value for this option. Below is an example:
Model: ... actAs: Geographical: ~
Specifies the array of attributes for latitude column.
The name of the latitude column. Default: latitude
The type of the latitude column. Default: double
Specifies the array of attributes for longitude column.
The name of the longitude column. Default: longitude
The type of the longitude column. Default: double
The SoftDelete behavior overrides the delete() functionality and adds a deleted_at column. When delete() is called, instead of deleting the record from the database, a delete_at date is set. If you want this behavior to be configured for you automatically, enter tilde ('~') as a value for this option. Below is an example:
Model: ... actAs: SoftDelete: ~
You are required to enable DQL callbacks in order for all executed queries to have the dql callbacks executed on them. In the SoftDelete behavior they are used to filter the select statements to exclude all records where the deleted_at flag is set with an additional WHERE condition. To enable DQL callbacks set use_dql_callbacks attribute to true in the databases.yml file:
all: doctrine: ... param: ... attributes: use_dql_callbacks: true
The name of the deleted_at column. Default: deleted_at
The type of the deleted_at column. Default: timestamp
In this section you can define the array of tables options for the model. When Doctrine creates your table from your model these options will be set on the create table statement. If you add this section, it recalls all attributes which are specified in the global options section. So you have repeatedly define those attributes here.
Determines the type of the table engine will be used in the database for current table. Use this attribute for MySQL database. Possible values: <INNODB | MyISAM>
Specifies the collation for the current table (eg. utf8_unicode_ci).
Specifies the character set for the current table (eg. utf8).
Specifies «Order By» clause, which is by default added to select queries generated by Doctrine.
Specifies options which is used by symfony framework.
Specifies whether or not to generate filter classes. Possible values: <true | false> Default: true
Specifies whether or not to generate form classes. Possible values: <true | false> Default: true
This parameter specifies the array of attributes for model. Doctrine offers the ability to set attributes for your generated models directly in your schema files similar to how you would if you were manually writing your Doctrine_Record child classes.
Specifies what Doctrine should export when exporting classes to your database for creating your tables. Available values:
Possible values: <all | tables | none> Default: all
Specifies whether to tests validity of the record using the current data. Available values:
Possible values: <all | lengths | types | none>
Doctrine uses an identity map internally to make sure that multiple objects for one record in a database don't ever exist. If you fetch an object and modify some of its properties, then re-fetch that same object later, the modified properties will be overwritten by default. You can change this behavior for current table by changing the hydrate_overwrite attribute to false. Possible values: <true | false> Default: true
Specifies which query class Doctrine should return whenever you instantiate a new query for current table. The only requirement is that it extends the Doctrine_Query class. Default: Doctrine_Query
Specifies which collection class Doctrine should use whenever a new collection is instantiated for current table records. The only requirement is that it must extend Doctrine_Collection. Default: Doctrine_Collection
Specifies column which values will be used as element indexes in collections. By default Doctrine colelction key values are just a sequential numerical indexes. But sometimes you may not want to use normal indexing for collection elements. For example in some cases mapping primary keys as collection keys might be useful. Eg:
// we assume that coll_key attribute contains 'id' value // which is the primary key of a user table $users = $userTable->findAll(); foreach($users as $id => $user) { echo $id . $user->username; // here $id == $user->id }