When using Phalcon\Mvc\Model classes, which correspond to actual tables in the database, Phalcon needs to know essential information regarding those tables, such as fields, data types, primary and foreign keys as well as relationships. The Phalcon\Mvc\Model\MetaData object is offering this functionality, transparently querying the database and generating the necessary data from the database schema. The data can then be stored in a data store (such as Redis, APCu etc.) to ensure that the database is not queried for the schema every time a query is executed.
NOTE: During deployments to production, please ensure that you always invalidate the metaData cache so that database changes that propagated during your deployment are available in your application. The metaData cache will be rebuilt with all the necessary changes.
Retrieving the metadata is an expensive database operation and we certainly do not want to perform it every time we run a query. We can however use one of many adapters available in order to cache the metadata.
This adapter uses plain files to store metadata. (not for production)
This adapter uses the Alternative PHP Cache (APC) to store the table metadata. The extension must be present in your system for this metadata cache to work. If the server is restarted, the data will be lost. This adapter is suitable for production applications.
The adapter receives a Phalcon\Cache\AdapterFactory class in order to instantiate the relevant cache object. You can also pass an array with additional options for the cache to operate.
The default prefix is ph-mm-apcu- and the lifetime is 172,000 (48 hours).
This adapter uses the server’s memory to store the metadata cache. The cache is available only during the request, and then the cache is lost. This cache is more suitable for development, since it accommodates the frequent changes in the database during development.
You can use the orm.exception_on_failed_metadata_save option in your php.ini file to force the component to throw an exception if there is an error storing the metadata or if the target directory is not writeable.
The default strategy to obtain the model’s metadata is database introspection. Using this strategy, the information schema is used to identify the fields in a table, its primary key, nullable fields, data types, etc.
Using the introspection strategies presented above, Phalcon can obtain the metadata for each model automatically. However, you have the option to define the metadata manually. This strategy overrides any strategy that has been set on the metadata manager. Columns added, modified or removed from the mapped table must be manually updated in the model for everything to work properly.
To set the metadata, we use the metaData method in a model: