Symfony2. Database and Doctrine
-
Upload
vladimir-doroshenko -
Category
Technology
-
view
126 -
download
3
description
Transcript of Symfony2. Database and Doctrine
Symfony2
Database and Doctrine
ORM (Object-relational mapping)
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
Creating the database
$ php app/console doctrine:database:create
Creating an Entity Class// src/Volcano/VideostatusBundle/Entity/Clip.php
namespace Volcano\VideostatusBundle\Entity;
class Clip
{
protected $id;
protected $url;
protected $timeStart;
protected $timeFinish;
}
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
{ }
Creating Mapping Info
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
Creating Mapping Info
/**
* @ORM\Column(type="string", length=255)
*/
protected $url;
Creating Mapping Info
/**
* @ORM\Column(name="time_start", type="integer")
*/
protected $timeStart;
Generating Setters and Getters
$ php app/console doctrine:generate:entities | Volcano\VideostatusBundle\Entity\Clip
Creating the schema
$ php app/console doctrine:schema:update --force
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());
}
Unit Of Work
DB
Entity
EM
Persist
Application
Update
Delete
Flush
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')
);
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'));
}
Deleting object
$em = $this->getDoctrine()->getManager();
$clip = $em->getRepository('VolcanoVideostatusBundle:
Clip')
->find($id);
$em->remove($clip);
$em->flush();
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();
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();
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
{ }
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();
}
}
Relationships
Many To Many
Clip
Fun
Котята
Сиськи
Clip
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();
}
}
Many To Many Association/**
* @ORM\Entity
*/
class Tag
{
/**
* @ORM\ManyToMany(targetEntity="Clip", mappedBy="tags")
**/
private $clips;
public function __construct() {
$this->clips = new ArrayCollection();
}
}
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);
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());
}
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>
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;
}
}
Lifecycle Callbacks/**
* @ORM\Entity()
* @ORM\HasLifecycleCallbacks()
*/
class Clip
{
//....
/**
* @ORM\PrePersist
*/
public function setCreatedValue()
{
$this->created = new \DateTime();
}
}
Lifecycle Callbacks
● preRemove● postRemove● prePersist● postPersist● preUpdate● postUpdate
Gedmo 2 Doctrine Extensions/**
* @ORM\Entity
*/
class Clip
{
/*
* @Gedmo\Slug(fields={"title"}, unique=true)
*/
protected $slug;
protected $title;
}
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;
}
Gedmo 2 Doctrine Extensions
● Tree● Translatable● Sluggable● Timestampable● Loggable● Softdeleteable● Uploadable