Note that on April 30th 2021 Doctrine officially deprecated doctrine/cache when it released version v2.0.0, which deleted all cache implementations from that library.
Since then, they recommend using symfony/cache instead, a PSR-6 compliant implementation.
You only need it if you want to cache Doctrine metadata in production but there’s no downside to do it, so we’ll show how to set it up.
If you have not yet migrated to PHP8 or simply want to continue using traditional PHPDoc comments to annotate your entities you’ll also need to import the doctrine/annotations package, which used to be a dependency of doctrine/orm but since 2.10.0 is optional:
composer require doctrine/annotations
Define your first Entity
You can skip this step and use your actual Doctrine entities instead.
The following is just an example.
Note that it uses PHP8 attributes, convert them to PHPDoc annotations if you need to.
Provide database credentials
Next, add the Doctrine settings alongside your Slim configuration.
Define the EntityManager service
Now we define the EntityManager service, which is the main point of interaction with the ORM in your code.
Slim 4 requires that you provide your own PSR-11 container implementation.
This example uses uma/dic, a simple and concise PSR-11 container.
Adapt this to your own choice of container.
Traditionally the annotation metadata reader was the most popular, but starting from doctrine/orm 2.10.0 they made the dependency on doctrine/annotations optional, hinting that the project prefers users to migrate to the modern PHP8 attribute notation.
Here we show how to configure the metadata reader with PHP8 attributes.
If you have not yet migrated to PHP8 or want to use traditional PHPDoc annotations you’ll need to explicitly require doctrine/annotations with Composer and call Setup::createAnnotationMetadataConfiguration(...) instead of Setup::createAttributeMetadataConfiguration(...) as in the following example.
Create the Doctrine console
To run database migrations, validate class annotations and so on you will create the doctrine CLI application.
This file just needs to retrieve the EntityManager service we just defined in our container and pass it to ConsoleRunner::run(new SingleManagerProvider($em)).
It is customary to create this file without the .php extension and make it executable.
It can be placed at the root of the project or a bin/ subdirectory.
The file begins with #!/usr/bin/env php and can be made executable with the chmod +x doctrine command on Linux.
Take a moment to verify that the console app works.
When properly configured, its output will look more or less like this:
At this point you can initialize the database and load the schema by running php vendor/bin/doctrine orm:schema-tool:create.
Using the EntityManager in our own code
Congratulations!
You can now manage your database from the command line and use the EntityManager wherever you need it in your code.