I’m in the middle of migrating my project from CakePHP ORM to new ORM. I’m using Cycle ORM. Official documentation recommends caching compiled schema to improve performance. I decided to cache schema on first request, store it on disk as a PHP code that return an array with schema. Thanks to that it can be put to Opcache.
Example code
First need to use schema renderer to print schema as PHP array:
composer require cycle/schema-renderer
Then in your code to retrieve SchemaInterface
instance for building ORM you can have:
private function generateSchema(DatabaseManager $dbal) : SchemaInterface
{
//Try to load cached schema.
$cachedSchema = @include $this->getCachePath();
//If cached schema is available, use it.
if (isset($cachedSchema) && $cachedSchema !== false) {
$schemaObject = new \Cycle\ORM\Schema($cachedSchema);
} else {
//If cached schema is not available, generate it.
$schema = $this->createSchemaInstance($dbal);
$schemaObject = new \Cycle\ORM\Schema($schema);
$converter = new Schema\Renderer\SchemaToArrayConverter();
$schemaAsArray = $converter->convert($schemaObject);
$renderer = new Schema\Renderer\PhpSchemaRenderer();
$phpCodeSchema = $renderer->render($schemaAsArray);
file_put_contents($this->getCachePath(), $phpCodeSchema);
}
return $schemaObject;
}
I ship my code to production via docker containers. Image is built without cache files so no need to worry about cache invalidation during release.
How to get DatabaseManager
instance, you can read here.