Slide 1

Slide 1 text

Doctrine More than just an ORM Andreas Braun @alcaeus

Slide 2

Slide 2 text

https://tsf.team/

Slide 3

Slide 3 text

Let’s go back in time

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

class Email extends Doctrine_Record { public function setTableDefinition() { $this->hasColumn('id', 'integer'); $this->hasColumn('email', 'string'); } public function setUp() { $this->hasOne('User', array( 'local' => 'user_id', 'foreign' => 'id' )); } }

Slide 6

Slide 6 text

$email = new Email(); $email->email = '[email protected]'; $email->user = new User(); $email->save();

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

No content

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

No content

Slide 13

Slide 13 text

No content

Slide 14

Slide 14 text

No content

Slide 15

Slide 15 text

No content

Slide 16

Slide 16 text

A look below the surface

Slide 17

Slide 17 text

$ composer require doctrine/orm Using version ^2.6 for doctrine/orm Package operations: 14 installs, 0 updates, 0 removals - Installing symfony/polyfill-mbstring (v1.9.0) - Installing symfony/console (v4.1.6) - Installing doctrine/instantiator (1.1.0) - Installing doctrine/event-manager (v1.0.0) - Installing doctrine/cache (v1.8.0) - Installing doctrine/dbal (v2.8.0) - Installing doctrine/lexer (v1.0.1) - Installing doctrine/annotations (v1.6.0) - Installing doctrine/reflection (v1.0.0) - Installing doctrine/collections (v1.5.0) - Installing doctrine/persistence (v1.0.1) - Installing doctrine/inflector (v1.3.0) - Installing doctrine/common (v2.9.0) - Installing doctrine/orm (v2.6.2) Writing lock file Generating autoload files

Slide 18

Slide 18 text

$ composer require symfony/maker-bundle [...] $ ./bin/console make:entity Email created: src/Entity/Email.php created: src/Repository/EmailRepository.php Entity generated! Now let's add some fields! New property name (press to stop adding fields): > email Field type (enter ? to see all types) [string]: > Field length [255]: > Can this field be null in the database (nullable) (yes/no) [no]: >

Slide 19

Slide 19 text

class Email { private $id; private $email; public function __construct(string $email) { $this->email = $email; } public function getEmail(): string { return $this->email; } }

Slide 20

Slide 20 text

/** * @method Email|null find($id, $lockMode = null, $lockVersion = null) * @method Email|null findOneBy(array $criteria, array $orderBy = null) * @method Email[] findAll() * @method Email[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class EmailRepository extends ServiceEntityRepository { public function __construct(RegistryInterface $registry) { parent::__construct($registry, Email::class); } }

Slide 21

Slide 21 text

namespace Doctrine\Common\Persistence; /** * Contract for a Doctrine persistence layer ObjectManager class to implement. */ interface ObjectManager {} /** * Contract for a Doctrine persistence layer repository class to implement. */ interface ObjectRepository {} /** * Contract for a Doctrine persistence layer ClassMetadata class to implement. */ interface ClassMetadata {} /** * Interface for proxy classes. */ interface Proxy {}

Slide 22

Slide 22 text

/** * @ORM\Entity(repositoryClass=EmailRepository::class) */ class Email { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $email; }

Slide 23

Slide 23 text

No content

Slide 24

Slide 24 text

/** * @Annotation * @Target("CLASS") */ final class SuperDuperClass { /** * @Required */ public $level; }

Slide 25

Slide 25 text

public function getSuperDuperClassLevel(string $className): ?int { $reader = new AnnotationReader(); $classAnnotations = $reader->getClassAnnotations(new ReflectionClass($className)); foreach ($classAnnotations as $annotation) { if ($annotation instanceof SuperDuperClass) { return $annotation->level; } } return null; }

Slide 26

Slide 26 text

use App\Annotation\SuperDuperClass; use Doctrine\ORM\Mapping as ORM; /** * @SuperDuperClass(level=5) * @ORM\Entity(repositoryClass=EmailRepository::class) */ class Email

Slide 27

Slide 27 text

class User { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $username; /** * @ORM\OneToMany(targetEntity=Email::class, mappedBy="user", orphanRemoval=true) */ private $emails; }

Slide 28

Slide 28 text

/** * @return Collection|Email[] */ public function getEmails(): Collection { return $this->emails; } public function addEmail(Email $email): void { if (!$this->emails->contains($email)) { $this->emails[] = $email; $email->setUser($this); } }

Slide 29

Slide 29 text

No content

Slide 30

Slide 30 text

/** * Returns a word in singular form. * * @param string $word The word in plural form. * * @return string The word in singular form. */ public function singularize(string $word) : string; /** * Returns a word in plural form. * * @param string $word The word in singular form. * * @return string The word in plural form. */ public function pluralize(string $word) : string;

Slide 31

Slide 31 text

No content

Slide 32

Slide 32 text

$ ./bin/console make:migration Success! Next: Review the new migration "src/Migrations/Version20180922042910.php" Then: Run the migration with php bin/console doctrine:migrations:migrate See https://symfony.com/doc/current/bundles/DoctrineMigrationsBundle/index.html

Slide 33

Slide 33 text

No content

Slide 34

Slide 34 text

final class Version20180922042910 extends AbstractMigration { public function up(Schema $schema) : void { // ... } public function down(Schema $schema) : void { $this->addSql('ALTER TABLE email DROP FOREIGN KEY FK_E7927C74A76ED395'); $this->addSql('DROP TABLE email'); $this->addSql('DROP TABLE user'); } }

Slide 35

Slide 35 text

$ ./bin/console doctrine:migrations:migrate Application Migrations Migrating up to 20180922042910 from 0 ++ migrating 20180922042910 -> CREATE TABLE email [...] -> CREATE TABLE user [...] -> ALTER TABLE email ADD CONSTRAINT [...] ++ migrated (0.17s) ------------------------ ++ finished in 0.17s ++ 1 migrations executed ++ 3 sql queries

Slide 36

Slide 36 text

No content

Slide 37

Slide 37 text

doctrine: dbal: # configure these for your database server driver: 'pdo_mysql' server_version: '5.7' charset: utf8mb4 default_table_options: charset: utf8mb4 collate: utf8mb4_unicode_ci url: '%env(resolve:DATABASE_URL)%'

Slide 38

Slide 38 text

public function getListTableForeignKeysSQL($table) { $table = $this->normalizeIdentifier($table); $table = $this->quoteStringLiteral($table->getName()); return "SELECT alc.constraint_name, alc.DELETE_RULE, cols.column_name \"local_column\", cols.position, ( SELECT r_cols.table_name FROM user_cons_columns r_cols WHERE alc.r_constraint_name = r_cols.constraint_name AND r_cols.position = cols.position ) AS \"references_table\", ( SELECT r_cols.column_name FROM user_cons_columns r_cols WHERE alc.r_constraint_name = r_cols.constraint_name AND r_cols.position = cols.position ) AS \"foreign_column\" FROM user_cons_columns cols JOIN user_constraints alc ON alc.constraint_name = cols.constraint_name AND alc.constraint_type = 'R' AND alc.table_name = " . $table . " ORDER BY cols.constraint_name ASC, cols.position ASC"; }

Slide 39

Slide 39 text

- Installing doctrine/lexer (v1.0.1): Loading from cache - Installing doctrine/annotations (v1.6.0): Loading from cache - Installing doctrine/event-manager (v1.0.0): Loading from cache - Installing doctrine/collections (v1.5.0): Loading from cache - Installing doctrine/cache (v1.8.0): Loading from cache - Installing doctrine/persistence (v1.0.1): Loading from cache - Installing doctrine/inflector (v1.3.0): Loading from cache - Installing doctrine/common (v2.9.0): Loading from cache - Installing doctrine/instantiator (1.1.0): Loading from cache - Installing doctrine/dbal (v2.8.0): Loading from cache - Installing doctrine/migrations (v1.8.1): Loading from cache - Installing doctrine/orm (v2.6.2): Loading from cache

Slide 40

Slide 40 text

- Installing doctrine/lexer (v1.0.1): Loading from cache - Installing doctrine/annotations (v1.6.0): Loading from cache - Installing doctrine/event-manager (v1.0.0): Loading from cache - Installing doctrine/collections (v1.5.0): Loading from cache - Installing doctrine/cache (v1.8.0): Loading from cache - Installing doctrine/persistence (v1.0.1): Loading from cache - Installing doctrine/inflector (v1.3.0): Loading from cache - Installing doctrine/common (v2.9.0): Loading from cache - Installing doctrine/instantiator (1.1.0): Loading from cache - Installing doctrine/dbal (v2.8.0): Loading from cache - Installing doctrine/migrations (v1.8.1): Loading from cache - Installing doctrine/orm (v2.6.2): Loading from cache

Slide 41

Slide 41 text

No content

Slide 42

Slide 42 text

/** * @Route("/signup", name="signup") */ public function __invoke(EntityManager $em, string $username, string $email): Response { $user = new User($username); $user->addEmail(new Email($email)); $em->persist($user); $em->flush(); return $this->json([], 204); }

Slide 43

Slide 43 text

/** * @ORM\OneToMany(targetEntity="App\Entity\Email", mappedBy="user", orphanRemoval=true) */ private $emails; public function __construct() { $this->emails = new ArrayCollection(); } /** * @return Collection|Email[] */ public function getEmails(): Collection { return $this->emails; } public function addEmail(Email $email): self { if (!$this->emails->contains($email)) { $this->emails[] = $email; $email->setUser($this); } return $this; }

Slide 44

Slide 44 text

No content

Slide 45

Slide 45 text

interface Collection extends Countable, IteratorAggregate, ArrayAccess { public function add($element); public function clear(); public function contains($element); public function isEmpty(); public function remove($key); // ... }

Slide 46

Slide 46 text

public function takeSnapshot() { $this->snapshot = $this->collection->toArray(); $this->isDirty = false; } public function getDeleteDiff() { return array_udiff_assoc( $this->snapshot, $this->collection->toArray(), function($a, $b) { return $a === $b ? 0 : 1; } ); } public function getInsertDiff() { return array_udiff_assoc( $this->collection->toArray(), $this->snapshot, function($a, $b) { return $a === $b ? 0 : 1; } ); }

Slide 47

Slide 47 text

class UserRepository extends ServiceEntityRepository { public function findOneByUsername(string $username): ?User { return $this->createQueryBuilder('u') ->andWhere('u.username = :username') ->setParameter('username', $username) ->getQuery() ->getOneOrNullResult() ; } }

Slide 48

Slide 48 text

class UserRepository extends ServiceEntityRepository { public function findOneByUsername(string $username): ?User { return $this->getEntityManager() ->createQuery('SELECT u FROM App\User u WHERE u.username = :username') ->setParameter('username', $username) ->getOneOrNullResult() ; } }

Slide 49

Slide 49 text

No content

Slide 50

Slide 50 text

protected function getCatchablePatterns() { return [ '[a-z_][a-z0-9_]*\:[a-z_][a-z0-9_]*(?:\\\[a-z_][a-z0-9_]*)*', // aliased name '[a-z_\\\][a-z0-9_]*(?:\\\[a-z_][a-z0-9_]*)*', // identifier or qualified name '(?:[0-9]+(?:[\.][0-9]+)*)(?:e[+-]?[0-9]+)?', // numbers "'(?:[^']|'')*'", // quoted strings '\?[0-9]*|:[a-z_][a-z0-9_]*' // parameters ]; }

Slide 51

Slide 51 text

No content

Slide 52

Slide 52 text

doctrine: orm: metadata_cache_driver: type: service id: doctrine.system_cache_provider query_cache_driver: type: service id: doctrine.system_cache_provider result_cache_driver: type: service id: doctrine.result_cache_provider

Slide 53

Slide 53 text

No content

Slide 54

Slide 54 text

No content

Slide 55

Slide 55 text

$serializedString = sprintf( '%s:%d:"%s":0:{}', self::SERIALIZATION_FORMAT_AVOID_UNSERIALIZER, strlen($className), $className ); return unserialize($serializedString);

Slide 56

Slide 56 text

use Doctrine\Instantiator\Instantiator; final class Dummy { private $foo; public function __construct(string $foo) { $this->foo = $foo; } public function getFoo(): string { return $this->foo; } } (new Instantiator())->instantiate(Dummy::class);

Slide 57

Slide 57 text

class Dummy#4 (1) { private $foo => NULL } Uncaught TypeError: Return value of Dummy::getFoo() must be of the type string, null returned

Slide 58

Slide 58 text

$ composer require stof/doctrine-extensions-bundle Using version ^1.3 for stof/doctrine-extensions-bundle ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Restricting packages listed in "symfony/symfony" to "4.1.*" Prefetching 3 packages - Downloading (100%) Package operations: 3 installs, 0 updates, 0 removals - Installing behat/transliterator (v1.2.0): Loading from cache - Installing gedmo/doctrine-extensions (v2.4.36): Loading from cache - Installing stof/doctrine-extensions-bundle (v1.3.0): Loading from cache

Slide 59

Slide 59 text

class User { // ... /** * @ORM\Column(type="datetime") * @Gedmo\Timestampable(on="create") */ private $createdAt; }

Slide 60

Slide 60 text

final class Events { const preRemove = 'preRemove'; const postRemove = 'postRemove'; const prePersist = 'prePersist'; const postPersist = 'postPersist'; const preUpdate = 'preUpdate'; const postUpdate = 'postUpdate'; const postLoad = 'postLoad'; const loadClassMetadata = 'loadClassMetadata'; const onClassMetadataNotFound = 'onClassMetadataNotFound'; const preFlush = 'preFlush'; const onFlush = 'onFlush'; const postFlush = 'postFlush'; const onClear = 'onClear'; }

Slide 61

Slide 61 text

No content

Slide 62

Slide 62 text

- Installing doctrine/lexer (v1.0.1): Loading from cache - Installing doctrine/annotations (v1.6.0): Loading from cache - Installing doctrine/event-manager (v1.0.0): Loading from cache - Installing doctrine/collections (v1.5.0): Loading from cache - Installing doctrine/cache (v1.8.0): Loading from cache - Installing doctrine/persistence (v1.0.1): Loading from cache - Installing doctrine/inflector (v1.3.0): Loading from cache - Installing doctrine/common (v2.9.0): Loading from cache - Installing doctrine/instantiator (1.1.0): Loading from cache - Installing doctrine/dbal (v2.8.0): Loading from cache - Installing doctrine/migrations (v1.8.1): Loading from cache - Installing doctrine/orm (v2.6.2): Loading from cache

Slide 63

Slide 63 text

- Installing doctrine/lexer (v1.0.1): Loading from cache - Installing doctrine/annotations (v1.6.0): Loading from cache - Installing doctrine/event-manager (v1.0.0): Loading from cache - Installing doctrine/collections (v1.5.0): Loading from cache - Installing doctrine/cache (v1.8.0): Loading from cache - Installing doctrine/persistence (v1.0.1): Loading from cache - Installing doctrine/inflector (v1.3.0): Loading from cache - Installing doctrine/common (v2.9.0): Loading from cache - Installing doctrine/instantiator (1.1.0): Loading from cache - Installing doctrine/dbal (v2.8.0): Loading from cache - Installing doctrine/migrations (v1.8.1): Loading from cache - Installing doctrine/orm (v2.6.2): Loading from cache

Slide 64

Slide 64 text

$ composer require doctrine/coding-standard Using version ^5.0 for doctrine/coding-standard ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Restricting packages listed in "symfony/symfony" to "4.1.*"

Slide 65

Slide 65 text

No content

Slide 66

Slide 66 text

/** * @author alcaeus * @since 1.0 */ final class Email { private $email; /** * @param string $email * @return void */ public function setEmail($email) { $this->email = $email; } /** * @return string|null */ public function getEmail() { return $this->email; } }

Slide 67

Slide 67 text

$ vendor/bin/phpcbf src/Email.php PHPCBF RESULT SUMMARY ---------------------------------------------------------------------- FILE FIXED REMAINING ---------------------------------------------------------------------- src/Email.php 7 1 ---------------------------------------------------------------------- A TOTAL OF 7 ERRORS WERE FIXED IN 1 FILE ---------------------------------------------------------------------- Time: 203ms; Memory: 10Mb $ vendor/bin/phpcs src/Email.php FILE: src/Email.php ------------------------------------------------------------------------ FOUND 1 ERROR AFFECTING 1 LINE ------------------------------------------------------------------------ 9 | ERROR | Property \App\Email::$email does not have @var annotation. ------------------------------------------------------------------------ Time: 124ms; Memory: 8Mb

Slide 68

Slide 68 text

final class Email { private $email; public function setEmail(string $email) : void { $this->email = $email; } public function getEmail() : ?string { return $this->email; } }

Slide 69

Slide 69 text

Slide 70

Slide 70 text

No content

Slide 71

Slide 71 text

No content

Slide 72

Slide 72 text

No content

Slide 73

Slide 73 text

No content

Slide 74

Slide 74 text

No content

Slide 75

Slide 75 text

No content

Slide 76

Slide 76 text

No content

Slide 77

Slide 77 text

No content

Slide 78

Slide 78 text

No content

Slide 79

Slide 79 text

No content

Slide 80

Slide 80 text

No content

Slide 81

Slide 81 text

No content

Slide 82

Slide 82 text

Thanks! @alcaeus github.com/alcaeus @doctrineproject https://joind.in/talk/2876c