After creating a metadata factory and metadata drivers, we now need a way to cache the metadata, since collecting them at each request is way too inefficient. Luckily, the Metadata library provides us with a FileCache (though it may be any kind of a cache, as long as it implements the same CacheInterface). First, we make the FileCache available as a service, and add a call to setCache on the metadata factory:

Prepare the cache directory

The FileCache needs to be told where to save the cached metadata to - a directory. We obviously want to place the metadata cache directory inside the cache directory used by the framework. The location of this directory is available as the kernel.cache_dir parameter. We can resolve this parameter using $container->getParameterBag()->resolveValue() to it's real value when we are inside the MatthiasAnnotationExtension::load() method. Then we make the resolved value (i.e. the real location of the cache directory) the first argument of the cache service, only after we have created it (if it does not already exist):

Prepare the PropertyMetadata for caching

When things need to be cached, they should be prepared for it. As you may remember, we stored the default value for properties as the public property $defaultValue of the custom PropertyMetadata class. Inside the serialize() and unserialize() methods, we need to take this $defaultValue into account, otherwise, it won't be cached and thus will not survive another request. Looking at the parent methods, we should also take into account the values for PropertyMetadata::$class and PropertyMetadata::$name:

Take a look at the cache

After a first round using the infamous DefaultValueProcessor I created in my first post about this subject, we now have inside the cache directory a file called Matthias-AnnotationBundle-Data-SomeClass.cache.php. Indeed, it contains the serialized data: