17/11/2015 - DOCTRINE, MONGODB, SYMFONY
This example depends on two documents (one League
can have many Team
s) for bi-directional one to many referencing and shows us how to use MongoDB as database for our application. The reference to the parent League
document is stored in Team
document. For more info visit DoctrineMongoDBBundle, QueryBuilder API, Reference Mapping, Bi-Directional References and Working with Objects.
services:
application_nosql.controller.team:
class: Application\NosqlBundle\Controller\TeamController
arguments:
- @doctrine_mongodb.odm.default_document_manager
- @application_nosql.repository.league
- @application_nosql.repository.team
services:
application_nosql.repository.default:
class: Application\NosqlBundle\Repository\DefaultRepository
factory: [@doctrine_mongodb, getRepository]
arguments: [Application\NosqlBundle\Document\League]
application_nosql.repository.team:
class: Application\NosqlBundle\Repository\TeamRepository
factory: [@doctrine_mongodb, getRepository]
arguments: [Application\NosqlBundle\Document\Team]
For now, I've just kept all in controller below but in real life, you should use service, model and factory classes along with controller to divide the logic.
namespace Application\NosqlBundle\Controller;
use Application\NosqlBundle\Document\League;
use Application\NosqlBundle\Document\Team;
use Application\NosqlBundle\Repository\LeagueRepository;
use Application\NosqlBundle\Repository\TeamRepository;
use DateTime;
use Doctrine\ODM\MongoDB\DocumentManager;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* @Route("/team", service="application_nosql.controller.team")
*/
class TeamController extends Controller
{
private $documentManager;
private $leagueRepository;
private $teamRepository;
public function __construct(
DocumentManager $documentManager,
LeagueRepository $leagueRepository,
TeamRepository $teamRepository
) {
$this->documentManager = $documentManager;
$this->leagueRepository = $leagueRepository;
$this->teamRepository = $teamRepository;
}
/**
* @param Request $request
* @param string $leagueId
*
* @Route("/{leagueId}")
* @Method({"POST"})
*
* @return Response
*/
public function createAction(Request $request, $leagueId)
{
$league = $this->leagueRepository->findOneByProperty('id', $leagueId);
if (!$league instanceof League) {
throw new NotFoundHttpException(
sprintf('League with id [%s] cannot be found.', $leagueId)
);
}
$team = new Team();
$team->setName($request->request->get('name'));
$team->setLeague($league);
$this->documentManager->persist($team);
$this->documentManager->flush();
return new Response('Team ID:'.json_encode($team->getId()));
}
/**
* @param string $property
* @param string $data
*
* @Route("/league/{property}/{data}")
* @Method({"GET"})
*
* @return Response
*/
public function getAllLeagueTeamsAction($property, $data)
{
$league = $this->leagueRepository->findOneByProperty($property, $data);
if (!$league instanceof League) {
throw new NotFoundHttpException(
sprintf('League with %s [%s] cannot be found.', $property, $data)
);
}
$i = 0;
$result = [];
$teams = $league->getTeams();
foreach ($teams as $team) {
$result[$i]['id'] = (string)$team->getId();
$result[$i]['name'] = $team->getName();
$result[$i]['createdAt'] = $team->getCreatedAt()->format(DateTime::ISO8601);
$i++;
}
return new Response(json_encode($result));
}
/**
* @param string $property
* @param string $data
*
* @Route("/{property}/{data}")
* @Method({"GET"})
*
* @return Response
*/
public function getOneTeamAction($property, $data)
{
$team = $this->teamRepository->findOneByProperty($property, $data);
if (!$team instanceof Team) {
throw new NotFoundHttpException(
sprintf('Team with %s [%s] cannot be found.', $property, $data)
);
}
$result['id'] = (string)$team->getId();
$result['name'] = $team->getName();
$result['createdAt'] = $team->getCreatedAt()->format(DateTime::ISO8601);
$result['league']['id'] = (string)$team->getLeague()->getId();
$result['league']['name'] = $team->getLeague()->getName();
return new Response(json_encode($result));
}
/**
* @param Request $request
* @param string $id
*
* @Route("/{id}")
* @Method({"PATCH"})
*
* @return Response
*/
public function updateTeamAction(Request $request, $id)
{
$team = $this->teamRepository->findOneByProperty('id', $id);
if (!$team instanceof Team) {
throw new NotFoundHttpException(
sprintf('Team with id [%s] cannot be found.', $id)
);
}
$team->setName($request->request->get('name'));
$this->documentManager->flush();
return new Response('Team ID:'.$id);
}
/**
* @param string $id
*
* @Route("/{id}")
* @Method({"DELETE"})
*
* @return Response
*/
public function deleteTeamAction($id)
{
$team = $this->teamRepository->findOneByProperty('id', $id);
if (!$team instanceof Team) {
throw new NotFoundHttpException(
sprintf('Team with id [%s] cannot be found.', $id)
);
}
$this->documentManager->remove($team);
$this->documentManager->flush();
return new Response('Team ID:'.$id);
}
}
namespace Application\NosqlBundle\Document;
namespace Application\NosqlBundle\Document;
use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Doctrine\ODM\MongoDB\Mapping\Annotations\Date;
use Doctrine\ODM\MongoDB\Mapping\Annotations\Id;
/**
* @MongoDB\Document(collection="league", repositoryClass="Application\NosqlBundle\Repository\LeagueRepository")
* @MongoDB\HasLifecycleCallbacks
*/
class League
{
/**
* @MongoDB\Id
*/
private $id;
/**
* @MongoDB\String
*/
private $name;
/**
* @MongoDB\Date
*/
private $createdAt;
/**
* @MongoDB\Date
*/
private $updatedAt;
/**
* @MongoDB\ReferenceMany(targetDocument="Team", mappedBy="league")
*/
private $teams;
public function __construct()
{
$this->teams = new ArrayCollection();
}
/**
* @MongoDB\PrePersist
*/
public function onPrePersist()
{
$this->createdAt = new DateTime();
}
/**
* @MongoDB\PreUpdate
*/
public function onPreUpdate()
{
$this->updatedAt = new DateTime();
}
/**
* @return id $id
*/
public function getId()
{
return $this->id;
}
/**
* @param string $name
*
* @return self
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @return string $name
*/
public function getName()
{
return $this->name;
}
/**
* @return date $createdAt
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @return date $updatedAt
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* @param Team $team
*/
public function addTeam(Team $team)
{
$this->teams[] = $team;
}
/**
* @param Team $team
*/
public function removeTeam(Team $team)
{
$this->teams->removeElement($team);
}
/**
* @return Collection $teams
*/
public function getTeams()
{
return $this->teams;
}
}
namespace Application\NosqlBundle\Document;
use DateTime;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Doctrine\ODM\MongoDB\Mapping\Annotations\Date;
use Doctrine\ODM\MongoDB\Mapping\Annotations\Id;
/**
* @MongoDB\Document(collection="team", repositoryClass="Application\NosqlBundle\Repository\TeamRepository")
* @MongoDB\HasLifecycleCallbacks
*/
class Team
{
/**
* @MongoDB\Id
*/
private $id;
/**
* @MongoDB\String
*/
private $name;
/**
* @MongoDB\Date
*/
private $createdAt;
/**
* @MongoDB\Date
*/
private $updatedAt;
/**
* @MongoDB\ReferenceOne(targetDocument="League", inversedBy="teams")
*/
private $league;
/**
* @MongoDB\PrePersist
*/
public function onPrePersist()
{
$this->createdAt = new DateTime();
}
/**
* @MongoDB\PreUpdate
*/
public function onPreUpdate()
{
$this->updatedAt = new DateTime();
}
/**
* @return id $id
*/
public function getId()
{
return $this->id;
}
/**
* @param string $name
*
* @return self
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @return string $name
*/
public function getName()
{
return $this->name;
}
/**
* @return date $createdAt
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @return date $updatedAt
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* @param League $league
*
* @return self
*/
public function setLeague(League $league)
{
$this->league = $league;
return $this;
}
/**
* @return League $league
*/
public function getLeague()
{
return $this->league;
}
}
namespace Application\NosqlBundle\Repository;
use Doctrine\ODM\MongoDB\DocumentRepository;
class LeagueRepository extends DocumentRepository
{
/**
* @param string $field
* @param string $data
*
* @return array|null|object
*/
public function findOneByProperty($field, $data)
{
return
$this->createQueryBuilder('League')
->field($field)->equals($data)
->getQuery()
->getSingleResult();
}
}
namespace Application\NosqlBundle\Repository;
use Doctrine\ODM\MongoDB\DocumentRepository;
class TeamRepository extends DocumentRepository
{
/**
* @return mixed
*/
public function findAll()
{
return
$this->createQueryBuilder('Team')
->sort('createdAt', 'desc')
->getQuery()
->execute();
}
/**
* @param string $field
* @param string $data
*
* @return array|null|object
*/
public function findOneByProperty($field, $data)
{
return
$this->createQueryBuilder('Team')
->field($field)->equals($data)
->getQuery()
->getSingleResult();
}
}
db.getCollection('league').find({})
/* 1 */
{
"_id" : ObjectId("564cbc35dd576ebcf90041aa"),
"name" : "Premiership",
"createdAt" : ISODate("2015-11-18T17:58:13.000Z")
}
/* 2 */
{
"_id" : ObjectId("564cbc49dd576ebbf90041ac"),
"name" : "Super Lig",
"createdAt" : ISODate("2015-11-18T17:58:33.000Z")
}
db.getCollection('team').find({})
/* 1 */
{
"_id" : ObjectId("564cbce9dd576ef2f80041ac"),
"name" : "Fenerbahce",
"createdAt" : ISODate("2015-11-18T18:01:13.000Z"),
"league" : {
"$ref" : "league",
"$id" : ObjectId("564cbc49dd576ebbf90041ac"),
"$db" : "inanzzz_mongodb_database"
}
}
/* 2 */
{
"_id" : ObjectId("564cbcf1dd576e1ef90041ad"),
"name" : "Besiktas",
"createdAt" : ISODate("2015-11-18T18:01:21.000Z"),
"league" : {
"$ref" : "league",
"$id" : ObjectId("564cbc49dd576ebbf90041ac"),
"$db" : "inanzzz_mongodb_database"
}
}
POST /nosql/team/564cbc49dd576ebbf90041ac
{
"name": "Fenerbahce"
}
{
"name": "Besiktas"
}
GET /nosql/team/league/id/564cbc49dd576ebbf90041ac
[
{
"id": "564cbce9dd576ef2f80041ac",
"name": "Fenerbahce",
"createdAt": "2015-11-18T18:01:13+0000"
},
{
"id": "564cbcf1dd576e1ef90041ad",
"name": "Besiktas",
"createdAt": "2015-11-18T18:01:21+0000"
}
]
GET /nosql/team/id/564cbcf1dd576e1ef90041ad
{
"id": "564cbcf1dd576e1ef90041ad",
"name": "Besiktas",
"createdAt": "2015-11-18T18:01:21+0000",
"league": {
"id": "564cbc49dd576ebbf90041ac",
"name": "Super Lig"
}
}
PATCH /nosql/team/564cbcf1dd576e1ef90041ad
{
"name": "Sekiztas"
}
DELETE /nosql/team/564cbcf1dd576e1ef90041ad