Skip to content

Instantly share code, notes, and snippets.

@rogeriopradoj
Created April 10, 2019 14:43
Show Gist options
  • Save rogeriopradoj/272f9d8d560f40dad05e5baa3b6f0ed5 to your computer and use it in GitHub Desktop.
Save rogeriopradoj/272f9d8d560f40dad05e5baa3b6f0ed5 to your computer and use it in GitHub Desktop.
<?php
namespace Alura\Doctrine\Mapping;
use Alura\Doctrine\Entity\Aluno;
use Alura\Doctrine\Entity\Curso;
use Alura\Doctrine\Entity\Telefone;
use Alura\Doctrine\Repository\AlunoRepository;
use LaravelDoctrine\Fluent\EntityMapping;
use LaravelDoctrine\Fluent\Fluent;
class AlunoMapping extends EntityMapping
{
public function mapFor(): string
{
return Aluno::class;
}
public function map(Fluent $builder)
{
$builder
->entity()
->setRepositoryClass(AlunoRepository::class);
$builder->increments('id');
$builder->string('nome');
$builder
->oneToMany(Telefone::class, 'telefones')
->mappedBy('aluno')
->cascadePersist()
->cascadeRemove()
->fetchEager();
$builder
->manyToMany(Curso::class, 'cursos')
->mappedBy('alunos');
}
}
<?php
namespace Alura\Doctrine\Mapping;
use Alura\Doctrine\Entity\Aluno;
use Alura\Doctrine\Entity\Curso;
use LaravelDoctrine\Fluent\EntityMapping;
use LaravelDoctrine\Fluent\Fluent;
class CursoMapping extends EntityMapping
{
public function mapFor(): string
{
return Curso::class;
}
public function map(Fluent $builder)
{
$builder->increments('id');
$builder->string('nome');
$builder
->manyToMany(Aluno::class, 'alunos')
->inversedBy('cursos');
}
}
<?php
namespace Alura\Doctrine\Helper;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Tools\Setup;
use LaravelDoctrine\Fluent\FluentDriver;
class EntityManagerFactory
{
public function getEntityManager(): EntityManagerInterface
{
$rootDir = __DIR__ . '/../..';
$connection = [
'driver' => 'pdo_sqlite',
'path' => $rootDir . '/var/data/banco.sqlite',
];
$fluent = new FluentDriver([
\Alura\Doctrine\Mapping\AlunoMapping::class,
\Alura\Doctrine\Mapping\CursoMapping::class,
\Alura\Doctrine\Mapping\TelefoneMapping::class,
]);
$config = new Configuration();
$config->setProxyDir($rootDir . '/src/Proxy');
$config->setProxyNamespace('Alura\Doctrine\Proxy');
$config->setMetadataDriverImpl($fluent);
return EntityManager::create($connection, $config);
}
}
<?php
namespace Alura\Doctrine\Mapping;
use Alura\Doctrine\Entity\Aluno;
use Alura\Doctrine\Entity\Telefone;
use LaravelDoctrine\Fluent\EntityMapping;
use LaravelDoctrine\Fluent\Fluent;
class TelefoneMapping extends EntityMapping
{
public function mapFor(): string
{
return Telefone::class;
}
public function map(Fluent $builder)
{
$builder->increments('id');
$builder->string('numero');
$builder
->manyToOne(Aluno::class, 'aluno')
->inversedBy('telefones');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment