Install via Composer (recommended):
composer require doctrine/doctrine-bundle:^2.1
Ensure your composer.json includes Symfony 2.3+ and Doctrine DBAL/ORM dependencies.
Enable the Bundle:
Add to app/AppKernel.php:
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
Configure Database:
Edit app/config/config.yml:
doctrine:
dbal:
driver: "%database_driver%"
host: "%database_host%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: true
First Use Case:
Create an entity (e.g., src/AppBundle/Entity/User.php):
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/** @ORM\Entity */
class User {
/** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */
private $id;
/** @ORM\Column(type="string") */
private $name;
}
Run migrations:
php app/console doctrine:schema:update --force
Entity Management:
@ORM\*) or YAML/XML for mappings.php app/console doctrine:mapping:import AppBundle annotation
Repository Pattern:
Extend Doctrine\ORM\EntityRepository for custom queries:
namespace AppBundle\Entity;
use Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository {
public function findByName($name) {
return $this->createQueryBuilder('u')
->where('u.name = :name')
->setParameter('name', $name)
->getQuery()
->getResult();
}
}
DQL Queries:
Fetch data via EntityManager:
$users = $entityManager->createQuery('SELECT u FROM AppBundle:User u WHERE u.name = :name')
->setParameter('name', 'John')
->getResult();
Lifecycle Callbacks:
Hook into entity events (e.g., @ORM\PrePersist):
/** @ORM\PrePersist */
public function setCreatedAt() {
$this->createdAt = new \DateTime();
}
$form = $this->createFormBuilder($user)
->add('name')
->getForm();
/** @ORM\Column(type="string", length=50) @Assert\NotBlank */
private $name;
onFlush):
$eventManager->addEventListener(
\Doctrine\ORM\Events::onFlush,
function ($eventArgs) { /* ... */ }
);
Proxy Classes:
php app/console cache:clear
php app/console doctrine:query:sql "SELECT u FROM AppBundle:User u"
Circular References:
@ORM\Backpack or @ORM\Transient to break cycles.MySQL Joins:
Transaction Isolation:
setIsolationLevel() if needed.Query Logging:
Enable in config.yml:
doctrine:
dbal:
logging: true
Logs appear in app/logs/doctrine.dbal.
Schema Validation:
php app/console doctrine:schema:validate
Custom Types:
Register via Doctrine\DBAL\Types\Type:
$type = new CustomType();
$doctrine->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('custom', $type);
Event Subscribers:
Implement Doctrine\Common\EventSubscriber for ORM events.
Custom DQL Functions:
Register via Doctrine\ORM\Query\AST\Functions\FunctionNode:
$queryBuilder->addCustomDqlFunction('custom_func', 'AppBundle\Query\CustomFunc');
auto_mapping: true and mappings are configured for non-annotation setups.default or define multiple connections in dbal.connections.How can I help you explore Laravel packages today?