Doctrine ODM 

com D de Mongo 

Fortaleza-CE

Alessandro Feitoza 

  • PHP com Rapadura
  • Darkmira (França)
  • Darkmira Tour PHP

O que diabé doctrine?

Doctrine 

Biblioteca PHP com serviços de persistência e mapeamento

www.doctrine-project.org

Quem usa? 

DBAL
ORM

DBAL 

  • Serviços básicos: Insert, Select, Update, Delete
  • Transactions
  • É praticamente um PDO muito melhorado.

Database Abstraction Layer

ORM 

Object Relational Mapper

  • Mapeamento de Entidades
  • DQL
  • Chega de criar o banco de dados no PHPmyAdmin

Porque usar? 

  • Aumento de Produtividade
  • Bom design de software
  • extrai ao máximo o poder dos objetos
  • Aumento de Produtividade

Quando não usar? 

  • Quando não quiser
  • Quando não souber OO

Suporte a quais bancos

  • MySQL
  • PostgreSQL
  • Oracle
  • SQL Server

Tá, e o "D"? 

E bancos não relacionais?

ODM 

ODM 

Object Document Mapper

  • Mapear Documentos
  • Schema
  • CRUD
  • Transactions

Como faz?

Baixando

composer require alcaeus/mongo-php-adapter

composer require doctrine/mongodb-odm

Configurando

Configurando

/bin/console.php

Configurando

/bin/console.php

Documentos

<?php

namespace Application\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations\Document;
// use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/**
 * @Document(collection="user", repositoryClass="")
 */
class User
{

}

Fields

/**
 * @var string
 * @Id(name="id", type="string")
 */
private $id;

/**
 * @var string
 * @Field(name="name", type="string")
 */
private $name;

Fields

/**
 * @var string
 * @Field(name="email", type="string") @UniqueIndex()
 */
private $email;

/**
 * @var array
 * @Field(type="collection")
 */
private $roles = [];

Fields

/**
 * @var Address
 * @ODM\Raw()
 * @Field(type="raw")
 */
private $address;

Relacionamentos

Embebeda

use Doctrine\ODM\MongoDB\Mapping\Annotations\EmbeddedDocument;

/**
 * Class Address
 * @package Application\Document
 * 
 * @EmbeddedDocument()
 */
class Address
{

}

Embebeda

/**
 * @var Address
 * @ODM\EmbedOne(targetDocument="Address")
 */
private $address;

Commands


php bin/console.php odm:schema:create

HasLifecycleCallbacks

HasLifecycleCallbacks

/**
 * @var \DateTime
 * @Field(type="date", nullable=true)
 */
private $registered;

/**
 * @var \DateTime
 * @Field(type="date", nullable=true)
 */
private $updated;

HasLifecycleCallbacks

/**
 * @ODM\PrePersist()
 */
public function prePersist()
{
    $this->registered = new \DateTime();
}

/**
 * @ODM\PreUpdate()
 */
public function preUpdate()
{
    $this->updated = new \DateTime();
}

Repository

namespace Application\Repository;

use Application\Document\User;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\DocumentRepository;

class UserRepository extends DocumentRepository
{
    public function __construct(DocumentManager $documentManager)
    {
        parent::__construct(
            $documentManager,
            $documentManager->getUnitOfWork(),
            $documentManager->getClassMetadata(User::class)
        );
    }
}

Find

public function find($id, $lockMode = LockMode::NONE, $lockVersion = null)
{
    return parent::find($id, $lockMode, $lockVersion);
}

public function findBy(array $criteria, array $sort = null, $limit = null, $skip = null)
{
    return parent::findBy($criteria, $sort, $limit, $skip);
}

public function findAll()
{
    return parent::findAll();
}

public function findOneBy(array $criteria)
{
    return parent::findOneBy($criteria);
}

Persist

public function insert(User $user)
{
    $this->getDocumentManager()->persist($user);
}

Delete

public function deleteOne(User $user)
{
    $this->getDocumentManager()->remove($user);
}

QueryBuilder

public function findWithProjection(array $fields)
{
    $queryBuilder = $this->getDocumentManager()->createQueryBuilder();

    return $queryBuilder
        ->select($fields) // ['name', 'email']
        ->getQuery()->execute();
}

AggregationBuilder

public function findUserByPeriodRegister($initial, $final)
{
    $builder = $this->createAggregationBuilder();
    $builder
        ->match()
        ->field('registered')
        ->gte($initial)
        ->lt($final)
        ->field('status')
        ->equals(true);

    return $builder->execute();
}

E agora?

www.doctrine-project.org/projects/doctrine-mongodb-odm/en/1.2/

Q faço eu da vida sem vc?

Dúvidas?

bit.ly/dmt2019

Valeu o Boi!

Valeu Vaqueiro.

@feitozaAle

@alessandrofeitoza

https://github.com/alessandrofeitoza/doctrine-odm-example

Made with Slides.com