17/11/2015 - DOCTRINE, MONGODB, SYMFONY
Bu örnek bir döküman üzerine kuruludur. Daha fazla bilgi için DoctrineMongoDBBundle, QueryBuilder API, Reference Mapping ve Working with Objects sayfalarını ziyaret edebilirsiniz.
MongoDB'nin sisteminizde kurulu olduğunu ve php.ini içinde aktif hale getirildiğini varsayalım.
{
"require": {
"doctrine/mongodb-odm": "1.0.*@dev",
"doctrine/mongodb-odm-bundle": "3.0.*@dev"
},
}
php composer.phar update doctrine/mongodb-odm doctrine/mongodb-odm-bundle
# app/autoload.php
use Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver;
AnnotationDriver::registerAnnotationClasses();
# app/AppKernel.php
new Doctrine\Bundle\MongoDBBundle\DoctrineMongoDBBundle(),
# app/config/config.yml
doctrine_mongodb:
connections:
default:
server: mongodb://localhost:27017
options: {}
default_database: inanzzz_mongodb_database
document_managers:
default:
auto_mapping: true
retry_connect: 3
retry_query: 3
inanzzz$ mongod
services:
application_nosql.controller.default:
class: Application\NosqlBundle\Controller\DefaultController
arguments:
- @doctrine_mongodb.odm.default_document_manager
- @application_nosql.repository.default
services:
application_nosql.repository.default:
class: Application\NosqlBundle\Repository\DefaultRepository
factory: [@doctrine_mongodb, getRepository]
arguments: [Application\NosqlBundle\Document\League]
Şu an için tüm mantığı controller içinde tuttum ama normal hayatta controller ile birlike service, model ve factory class kullanmalısınız.
namespace Application\NosqlBundle\Controller;
use Application\NosqlBundle\Document\League;
use Application\NosqlBundle\Repository\LeagueRepository;
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("/league", service="application_nosql.controller.default")
*/
class DefaultController extends Controller
{
private $documentManager;
private $leagueRepository;
public function __construct(
DocumentManager $documentManager,
LeagueRepository $leagueRepository
) {
$this->documentManager = $documentManager;
$this->leagueRepository = $leagueRepository;
}
/**
* @param Request $request
*
* @Route("")
* @Method({"POST"})
*
* @return Response
*/
public function createLeagueAction(Request $request)
{
$league = new League();
$league->setName($request->request->get('name'));
$this->documentManager->persist($league);
$this->documentManager->flush();
return new Response('League ID:'.json_encode($league->getId()));
}
/**
* @Route("")
* @Method({"GET"})
*
* @return Response
*/
public function getAllLeagueAction()
{
$leagues = $this->leagueRepository->findAll();
$i = 0;
$result = [];
foreach ($leagues as $league) {
$result[$i]['id'] = (string)$league->getId();
$result[$i]['name'] = $league->getName();
$result[$i]['createdAt'] = $league->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 getOneLeagueAction($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)
);
}
$result['id'] = (string)$league->getId();
$result['name'] = $league->getName();
$result['createdAt'] = $league->getCreatedAt()->format(DateTime::ISO8601);
return new Response(json_encode($result));
}
/**
* @param Request $request
* @param string $id
*
* @Route("/{id}")
* @Method({"PATCH"})
*
* @return Response
*/
public function updateLeagueAction(Request $request, $id)
{
$league = $this->leagueRepository->findOneByProperty('id', $id);
if (!$league instanceof League) {
throw new NotFoundHttpException(
sprintf('League with id [%s] cannot be found.', $id)
);
}
$league->setName($request->request->get('name'));
$this->documentManager->flush();
return new Response('League ID:'.$id);
}
/**
* @param string $id
*
* @Route("/{id}")
* @Method({"DELETE"})
*
* @return Response
*/
public function deleteLeagueAction($id)
{
$league = $this->leagueRepository->findOneByProperty('id', $id);
if (!$league instanceof League) {
throw new NotFoundHttpException(
sprintf('League with id [%s] cannot be found.', $id)
);
}
$this->documentManager->remove($league);
$this->documentManager->flush();
return new Response('League ID:'.$id);
}
}
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="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\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;
}
}
namespace Application\NosqlBundle\Repository;
use Doctrine\ODM\MongoDB\DocumentRepository;
class LeagueRepository extends DocumentRepository
{
/**
* @return mixed
*/
public function findAll()
{
return
$this->createQueryBuilder('League')
->sort('createdAt', 'desc')
->getQuery()
->execute();
}
/**
* @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();
}
}
POST /app_dev.php/nosql/league
{
"name": "inanzzz"
}
GET /nosql/league/id/564bb9fcdd576e1ef90041ab
{
"id": "564bb9fcdd576e1ef90041ab",
"name": "inanzzz3",
"createdAt": "2015-11-17T23:36:28+0000"
}
GET /nosql/league
[
{
"id": "564bb9fcdd576e1ef90041ab",
"name": "inanzzz3",
"createdAt": "2015-11-17T23:36:28+0000"
},
{
"id": "564bb9f8dd576e1ef90041aa",
"name": "inanzzz2",
"createdAt": "2015-11-17T23:36:24+0000"
},
{
"id": "564bb9f4dd576e1ef90041a9",
"name": "inanzzz1",
"createdAt": "2015-11-17T23:36:20+0000"
}
]
PATCH /nosql/league/564bb9f8dd576e1ef90041aa
{
"name": "inanzzz2u"
}
DELETE /nosql/league/564bb9f4dd576e1ef90041a9