Symfony2. Database and Doctrine

32
Symfony2 Database and Doctrine

description

Symfony2. Database and Doctrine

Transcript of Symfony2. Database and Doctrine

Page 1: Symfony2. Database and Doctrine

Symfony2

Database and Doctrine

Page 2: Symfony2. Database and Doctrine

ORM (Object-relational mapping)

Page 3: Symfony2. Database and Doctrine

Configuring the Database

# app/config/parameters.yml

parameters:

database_driver: pdo_mysql

database_host: localhost

database_name: test_project

database_user: root

database_password: password

Page 4: Symfony2. Database and Doctrine

Creating the database

$ php app/console doctrine:database:create

Page 5: Symfony2. Database and Doctrine

Creating an Entity Class// src/Volcano/VideostatusBundle/Entity/Clip.php

namespace Volcano\VideostatusBundle\Entity;

class Clip

{

protected $id;

protected $url;

protected $timeStart;

protected $timeFinish;

}

Page 6: Symfony2. Database and Doctrine

Creating Mapping Info// src/Volcano/VideostatusBundle/Entity/Clip.php

namespace Volcano\VideostatusBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**

* @ORM\Entity

* @ORM\Table(name="clip", indexes={

* @ORM\Index(name="clip_url_idx",columns={"url"}

* })

*/

class Clip

{ }

Page 7: Symfony2. Database and Doctrine

Creating Mapping Info

/**

* @ORM\Id

* @ORM\Column(type="integer")

* @ORM\GeneratedValue(strategy="AUTO")

*/

protected $id;

Page 8: Symfony2. Database and Doctrine

Creating Mapping Info

/**

* @ORM\Column(type="string", length=255)

*/

protected $url;

Page 9: Symfony2. Database and Doctrine

Creating Mapping Info

/**

* @ORM\Column(name="time_start", type="integer")

*/

protected $timeStart;

Page 10: Symfony2. Database and Doctrine

Generating Setters and Getters

$ php app/console doctrine:generate:entities | Volcano\VideostatusBundle\Entity\Clip

Page 11: Symfony2. Database and Doctrine

Creating the schema

$ php app/console doctrine:schema:update --force

Page 12: Symfony2. Database and Doctrine

Persisting object// src/Volcano/VideostatusBundle/Controller/ClipController.php

use Symfony\Component\HttpFoundation\Response;

use Volcano\VideostatusBundle\Entity\Clip;

public function createAction()

{

$clip = new Clip();

$clip->setUrl('http://www.youtube.com/watch?v=PYtXuBN1Hvc');

$clip->setTimeStart(52);

$clip->setTimeFinish(54);

$em = $this->getDoctrine()->getManager();

$em->persist($clip);

$em->flush();

return new Response('Created clip id '.$clip->getId());

}

Page 13: Symfony2. Database and Doctrine

Unit Of Work

DB

Entity

EM

Persist

Application

Update

Delete

Flush

Page 14: Symfony2. Database and Doctrine

Fetching object

$repository = $this->getDoctrine()

->getRepository('VolcanoVideostatusBundle:Clip');

$clip = $repository->find($id);

$clip = $repository->findOneByUrl('http://www.youtube.com/watch?v=PYtXuBN1Hvc');

$clips = $repository->findByUrl('http://www.youtube.com/watch?v=PYtXuBN1Hvc');$clips = $repository->findAll();

$clips = $repository->findBy(

array('url' => 'http://www.youtube.com/watch?v=PYtXuBN1Hvc'), array('timeStart' => '0')

);

Page 15: Symfony2. Database and Doctrine

Updating objectpublic function updateAction($id)

{

$em = $this->getDoctrine()->getManager();

$clip = $em->getRepository('VolcanoVideostatusBundle:Clip')->find($id);

if (!$clip) {

throw $this->createNotFoundException(

'No clip found for id '.$id

);

}

$clip->setTimeFinish(55);

$em->flush();

return $this->redirect($this->generateUrl('homepage'));

}

Page 16: Symfony2. Database and Doctrine

Deleting object

$em = $this->getDoctrine()->getManager();

$clip = $em->getRepository('VolcanoVideostatusBundle:

Clip')

->find($id);

$em->remove($clip);

$em->flush();

Page 17: Symfony2. Database and Doctrine

DQL

$em = $this->getDoctrine()->getManager();

$query = $em->createQuery(

'SELECT c FROM VolcanoVideostatusBundle:Clip c WHERE c.

timeFinish - c.timeStart > :delta ORDER BY p.id ASC'

)->setParameter('delta', 10);

$clips = $query->getResult();

Page 18: Symfony2. Database and Doctrine

DQL - query builder$repository = $this->getDoctrine()

->getRepository('VolcanoVideostatusBundle:Clip');

$query = $repository->createQueryBuilder('c')

->where('c.timeFinish - c.timeStart > :delta')

->setParameter('delta', 10)

->orderBy('c.id', 'ASC')

->getQuery();

$clips = $query->getResult();

Page 19: Symfony2. Database and Doctrine

Custom Repository// src/Volcano/VideostatusBundle/Entity/Clip.php

namespace Volcano\VideostatusBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**

* @ORM\Entity(repositoryClass="Volcano\VideostatusBundle\Repository\ClipRepository")

* @ORM\Table(name="clip")

*/

class Clip

{ }

Page 20: Symfony2. Database and Doctrine

Custom Repository//src/Volcano/VideostatusBundle/Repository/ClipRepository.php

namespace Volcano\VideostatusBundle\Repository;

use Doctrine\ORM\EntityRepository;

class ClipRepository extends EntityRepository

{

public function findAllLongerThan($length)

{

$query = $repository->createQueryBuilder('c')

->where('c.timeFinish - c.timeStart > :delta')

->setParameter('delta', intval($length))

->orderBy('c.id', 'ASC')

->getQuery();

return $query->getResult();

}

}

Page 21: Symfony2. Database and Doctrine

Relationships

Many To Many

Clip

Fun

Котята

Сиськи

Clip

Page 22: Symfony2. Database and Doctrine

Many To Many Association/**

* @ORM\Entity

*/

class Clip

{

/**

* @ORM\ManyToMany(targetEntity="Tag", inversedBy="clips")

* @ORM\JoinTable(name="clips_tags")

**/

private $tags;

public function __construct() {

$this->groups = new ArrayCollection();

}

}

Page 23: Symfony2. Database and Doctrine

Many To Many Association/**

* @ORM\Entity

*/

class Tag

{

/**

* @ORM\ManyToMany(targetEntity="Clip", mappedBy="tags")

**/

private $clips;

public function __construct() {

$this->clips = new ArrayCollection();

}

}

Page 24: Symfony2. Database and Doctrine

Many To Many AssociationCREATE TABLE Clip (

id INT AUTO_INCREMENT NOT NULL,

PRIMARY KEY(id)

) ENGINE = InnoDB;

CREATE TABLE clips_tags (

clip_id INT NOT NULL,

tag_id INT NOT NULL,

PRIMARY KEY(clip_id, tag_id)

) ENGINE = InnoDB;

CREATE TABLE Tag (

id INT AUTO_INCREMENT NOT NULL,

PRIMARY KEY(id)

) ENGINE = InnoDB;

ALTER TABLE clips_tags ADD FOREIGN KEY (clip_id) REFERENCES Clip(id);

ALTER TABLE clips_tags ADD FOREIGN KEY (tag_id) REFERENCES Tag(id);

Page 25: Symfony2. Database and Doctrine

Persisting objectpublic function createAction()

{

$clip = new Clip();

$clip->setUrl('http://www.youtube.com/watch?v=PYtXuBN1Hvc'); $tag1 = new Tag();

$tag1->setName('Fun');

$tag2 = new Tag();

$tag2->setName('Котята');

$clip->addTag($tag1);

$clip->addTag($tag2);

$em = $this->getDoctrine()->getManager();

$em->persist($tag1);

$em->persist($tag2);

$em->persist($clip);

$em->flush();

return new Response('Created clip id '.$clip->getId());

}

Page 26: Symfony2. Database and Doctrine

Fetching Related Objectspublic function showClipTagsAction($id)

{

$clip = $this->getDoctrine()

->getRepository('VolcanoVideostatusBundle:Clip')->find($id);

$tags = $clip->getTags();

return array('tags' => $tags);

}

<div class="tags">

<div class="tags-list">

{% for tag in tags %}

<a class="label" href="#">{{tag.name}}</a>

{% endfor %}

</div>

</div>

Page 27: Symfony2. Database and Doctrine

Fetching Related Objects<?php

// src/Volcano/VideostatusBundle/Entity/ClipRepository.php

public function findOneByIdJoinedToTags($id)

{

$query = $this->getEntityManager()

->createQuery('

SELECT c, t FROM VideostatusBundle:Clip c

JOIN c.tags t

WHERE c.id = :id'

)->setParameter('id', $id);

try {

return $query->getSingleResult();

} catch (\Doctrine\ORM\NoResultException $e) {

return null;

}

}

Page 28: Symfony2. Database and Doctrine

Lifecycle Callbacks/**

* @ORM\Entity()

* @ORM\HasLifecycleCallbacks()

*/

class Clip

{

//....

/**

* @ORM\PrePersist

*/

public function setCreatedValue()

{

$this->created = new \DateTime();

}

}

Page 29: Symfony2. Database and Doctrine

Lifecycle Callbacks

● preRemove● postRemove● prePersist● postPersist● preUpdate● postUpdate

Page 30: Symfony2. Database and Doctrine

Gedmo 2 Doctrine Extensions/**

* @ORM\Entity

*/

class Clip

{

/*

* @Gedmo\Slug(fields={"title"}, unique=true)

*/

protected $slug;

protected $title;

}

Page 31: Symfony2. Database and Doctrine

Gedmo 2 Doctrine Extensionsclass Clip

{

/**

* @Gedmo\Timestampable(on="create")

* @ORM\Column(name="created", type="datetime")

*/

private $created;

/**

* @ORM\Column(name="updated", type="datetime")

* @Gedmo\Timestampable(on="update")

*/

private $updated;

}

Page 32: Symfony2. Database and Doctrine

Gedmo 2 Doctrine Extensions

● Tree● Translatable● Sluggable● Timestampable● Loggable● Softdeleteable● Uploadable