doctrine/doctrine-bundle
Symfony bundle integrating Doctrine DBAL and ORM. Provides database abstraction, schema tools, and an object-relational mapper with DQL for powerful queries, plus configuration and tooling that fits the Symfony ecosystem.
Installation:
composer require doctrine/doctrine-bundle
Add to config/bundles.php:
return [
Doctrine\Bundle\DoctrineBundle\DoctrineBundle::class => ['all' => true],
];
Configuration:
Define database connection in config/packages/doctrine.yaml:
doctrine:
dbal:
url: '%env(DATABASE_URL)%'
orm:
auto_generate_proxy_classes: true
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
auto_mapping: true
First Use Case:
Create an entity (src/Entity/Post.php):
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity]
class Post
{
#[ORM\Id, ORM\GeneratedValue, ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private string $title;
}
Run migrations:
php bin/console doctrine:migrations:diff
php bin/console doctrine:migrations:migrate
doctrine:schema:update --dump-sql (Preview SQL)doctrine:entity:generate (Generate entities from DB)doctrine:query:sql (Run raw SQL)$entityManager = $this->getDoctrine()->getManager();
$post = new Post();
$post->setTitle('Hello Doctrine');
$entityManager->persist($post);
$entityManager->flush();
$posts = $entityManager->getRepository(Post::class)->findAll();
$query = $entityManager->createQuery(
'SELECT p FROM App\Entity\Post p WHERE p.title LIKE :title'
)->setParameter('title', '%Doctrine%');
$results = $query->getResult();
php bin/console make:migration
php bin/console doctrine:migrations:migrate
# config/packages/doctrine.yaml
doctrine:
orm:
dql:
string_functions:
CONCAT: DoctrineExtensions\Query\Mysql\StringFunctions\MysqlConcat
// src/EventListener/PostListener.php
namespace App\EventListener;
use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
use Doctrine\ORM\Event\LifecycleEventArgs;
class PostListener implements EventSubscriberInterface
{
public function prePersist(LifecycleEventArgs $args): void
{
$post = $args->getObject();
$post->setCreatedAt(new \DateTime());
}
}
Register in services.yaml:
services:
App\EventListener\PostListener:
tags:
- { name: doctrine.event_subscriber }
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
$builder->add('author', EntityType::class, [
'class' => User::class,
'choice_label' => 'username',
]);
# config/packages/api_platform.yaml
api_platform:
formats:
jsonld:
mime_types: ['application/ld+json']
patch_formats:
json: ['application/merge-patch+json']
swagger:
versions: [3]
composer require gedmo/doctrine-extensions
Configure in doctrine.yaml:
gedmo_listener:
flushable: true
# config/packages/doctrine.yaml
doctrine:
dbal:
connections:
default:
url: '%env(DATABASE_URL)%'
read_replica:
url: '%env(READ_REPLICA_URL)%'
orm:
entity_managers:
default:
connection: default
mappings:
App:
is_bundle: false
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: App
read_only:
connection: read_replica
mappings:
App:
is_bundle: false
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: App
Class 'App\Entity\Proxy\__CG__Post' not foundphp bin/console doctrine:cache:clear-metadata
php bin/console cache:clear
auto_generate_proxy_classes is true and proxy_dir is writable.SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db.post' doesn't existnaming_strategy in doctrine.yaml:
doctrine:
orm:
naming_strategy: doctrine.orm.naming_strategy.underscore
Cannot determine table name for class "App\Entity\User" because its metadata is not yet loaded.lazy: true in associations:
#[ORM\ManyToOne(targetEntity: Post::class, inversedBy: 'authors', lazy: true)]
There are some new migrations, but you already have migrations in database.php bin/console doctrine:migrations:execute --down --dry-run
php bin/console doctrine:migrations:migrate
tags:
- { name: doctrine.event_subscriber, connection: default }
# config/packages/dev/doctrine.yaml
doctrine:
dbal:
logging: true
profiling: true
View logs in var/log/dev.log.
Install symfony/profiler-pack and enable:
# config/packages/dev/doctrine.yaml
framework:
profiler: { only_exceptions: false }
$query = $entityManager->createQuery('SELECT p FROM App\Entity\Post p');
dump($query->getSQL()); // Raw SQL
dump($query->getParameters()); // Parameters
php bin/console doctrine:schema:validate
auto_mapping options like controller_resolver are deprecated.mappings configuration:
doctrine:
orm:
auto_mapping: false
mappings:
App:
is_bundle: false
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: App
Invalid XML mapping fileenable_xsd_validation is true and XSD schemas are valid:
doctrine:
orm:
xml_validation: true
use_savepoints or disable_type_comments.use_savepoints was removed in v3.0.0).namespace App\Doctrine;
use Doctrine\ORM\Query\QueryBuilder;
class Post
How can I help you explore Laravel packages today?