I'm playing with Doctrine ODM, trying to make some i18n-able field in my Mongo document. This is what I want to achieve in Mongo:
{
"title": {
"en": "Car",
"eu": "Autoa"
}
}
And the PHP API I want for the Document would be something like this:
$doc->getTitle()->setDefaultLocale('en');
$doc->getTitle(); // "Car"
$doc->getTitle()->get('eu'); // "Autoa"
$doc->getTitle()->set('es', 'Coche');
$doc->getTitle()->setTranslations([
'fr' => 'Voiture',
'eu' => 'Kotxea',
]);
$doc->getTitle()->getTranslations(); // ["en" => "Car", ...]
I have tried two aproaches, both of them with it's own pitfalls. I don't like none of them.
Custom Annotation
I've created a class which will be the middleman between the document and mongo. This class will be placed in the field, in this case in $title.
class Translation
{
protected $default;
protected $translations;
public function __construct(array $translations = array()) { /* ... */ }
public function get($locale) { /* ... */ }
public function getTranslations() { /* ... */ }
public function set($locale, $value) { /* ... */ }
public function setDefaultLocale($default) { /* ... */ }
public function setTranslations(array $translations = array()) { /* ... */ }
}
Then, I've created a custom FieldType, which converts the Mongo array to the Translation middleman object and viceversa (convertTo* methods seem to be ignored by Doctrine and are equal to the closureTo* methods, so I'll omit them):
class TranslationType extends \Doctrine\ODM\MongoDB\Types\Type
{
public function convertToDatabaseValue($value) { /* ... */ }
public function convertToPHPValue($value) { /* ... */ }
public function closureToMongo()
{
return '$return = $value->getTranslations();';
}
public function closureToPHP()
{
return '$return = new \App\TransBundle\MongoDB\Translation($value);';
}
}
Then, I have my annotation:
/** #Annotation */
class Translation extends \Doctrine\ODM\MongoDB\Mapping\Annotations\AbstractField
{
public $type = 'translation';
}
And the document:
use App\TransBundle\MongoDB\Annotations\Translation;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/** #MongoDB\Document */
class Translated
{
/** #MongoDB\Id */
protected $id;
/** #Translation */
protected $title;
public function getId() { /* ... */ }
public function getTitle() { /* ... */ }
}
The GOOD parts:
Easy usage: one use, property declaration, annotation and the getter.
Reads OK from Mongo => Doctrine.
Meets API requirements.
The BAD parts:
Doesn't save to DB, I suppose that it's because the Translation object doesn't dirty the title property on the parent object Translated.
$title doesn't get initialized to the middleman Translation object on object creation.
This would be fixed by initializing the object in the constructor, but if possible I'd like to try to avoid this to keep the usage as lean as possible. I'll have to find a workaround.
EmbedOne
The second approach consists of using an embedded document, this works perfectly, but has it's own small issues. :-)
First, my base Translation class for the embedded document, this class will work directly on the class properties instead of an array property:
class BaseTranslation
{
public function __construct(array $translations = array()) { /* ... */ }
public function get($locale) { /* ... */ }
public function getTranslations() { /* ... */ }
public function set($locale, $value) { /* ... */ }
public function setDefaultLocale($default) { /* ... */ }
public function setTranslations(array $translations = array()) { /* ... */ }
}
Then, the Translation class to be used in my projects, this will be the actual embbeded document:
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/** #MongoDB\EmbeddedDocument */
class Translation extends BaseTranslation
{
/** #MongoDB\String */
protected $en;
/** #MongoDB\String */
protected $es;
/** #MongoDB\String */
protected $fr;
}
Finally the Document
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/** #MongoDB\Document */
class Translated
{
/** #MongoDB\Id */
protected $id;
/** #MongoDB\EmbedOne(targetDocument="Translation") */
protected $title;
public function getId() { /* ... */ }
public function getTitle() { /* ... */ }
}
The GOOD parts:
It just works, reads and writes nicely.
Easy setup.
Can be used with any data type, so it would be easy to add an isTranslated i18n boolean field, just add a new TranslationBoolean class.
The BAD parts:
Not a big problem but the locales are hardcoded in the Translation class, it would be nice to be able to work directly on an array but this would add another level in the schema and type coercion might be lost.
Like in the other approach, the property doesn't get initialized, but it's easy as initializing it in the constructor (like any One2Many relation).
Conclusions
I'm liking more the second approach, which works how it's now. Do you have any idea how to overcome the BAD parts on both approaches?
Thanks!
Regarding the type methods:
closureToMongo() is actually not used.
closureToPHP() is used by the HydratorFactory class.
convertToPHPValue() is used by ClassMetadataInfo, but only for identifiers.
convertToDatabaseValue() is used in a few places, such as UnitOfWork and PersistenceBuilder.
The missing convertToDatabaseValue() implementation could be related to why you're seeing TranslationType fail to persist to the database.
The issue of "hardcoded locales in the Translation class" could be alleviated by storing an object (Hash annotation) within this field, although that would add another layer to the model. An EmbedMany array of objects containing a field each for the language code and value would consume even more space, although the model could make it easier to devise a form to edit the data.
Have you looked into the DoctrineExtensions library? It contains a component for having translatable documents/entities (supports both ODM and ORM). The author has slowed down his own development of it, but there are a healthy amount of pull requests being merged on the project and it is widely used.
Related
TYPO3 Extbase - Failing to render json via typnum
Next to list/edit/new/remove action (which work) I tried to render the output in json. But no values render. If I do a simple ...
$data = array('value'=>'001');
return json_encode($data);
It does return ...
{"value":"001"}
What am I missing?
Edit: With using and referencing to the same repository its working:
JSONController.php
<?php
namespace Vendor\Lei\Controller;
use Vendor\Lei\Domain\Model\Lei;
/**
* JSONController
*/
class JSONController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController {
/**
* leiRepository
*
* #var \Vendor\Lei\Domain\Repository\LeiRepository
* #inject
*/
protected $leiRepository;
/**
* #var string
*/
protected $defaultViewObjectName = 'TYPO3\CMS\Extbase\Mvc\View\JsonView';
/**
* action jsonRequest
*
* #return void
*/
public function jsonRequestAction() {
//$data = array('value'=>'001');
//return json_encode($data);
$this->view->setVariablesToRender(array('records'));
$this->view->assign('records', $this->leiRepository->jsonRequest());
}
}
LeiRepository.php
<?php
namespace Vendor\Lei\Domain\Repository;
use TYPO3\CMS\Extbase\Persistence\QueryInterface;
class LeiRepository extends \TYPO3\CMS\Extbase\Persistence\Repository {
...
public function jsonRequest() {
$query = $this->createQuery();
$result = $query->setLimit(100)->execute();
return $result;
}
}
If you inject and use a JsonRepository extbase expexts a domain object called Json. If you just want to render already existing domain objects as their JSON representation, just use the same repositories you used in your listAction() and detailAction().
Have a look at my example: https://usetypo3.com/json-view.html
Also, a debug after the return like you did in your repository will never be executed.
i'm using symfony2 API platform to generate an api from my mongodb database but i get this error :
hydra:description: "No resource found for object of type "AppBundle\Document\article"",
i have two mongo db documents user and article and each user has multiple articles so i'm trying to list all the users with all their articles titles so i can get something like this :
{
#id: "/user/53edb6200cf2400d584c2617",
#type: "user",
class: "de.freelancer.mongo.domain.User",
email: "feer#de.com",
displayname: "feer",
withnewsletter: false,
language: "de_DE",
active: true,
admin: false,
articles : ['article1','article2','article3']
}
here is my code :
user Document
<?php
namespace AppBundle\Document;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Dunglas\ApiBundle\Annotation\Iri;
use Symfony\Component\Validator\Constraints as Assert;
/**
#MongoDB\Document
#MongoDB\Document(collection="user")
/
class User{
/*
#MongoDB\Id(strategy="AUTO") */
private $id;
/**
#MongoDB\ReferenceMany(targetDocument="articles", mappedBy="user") */
private $articles;
public function __construct()
{
$this->articles = new ArrayCollection();
}
/**
*/
public function getArticles()
{
return $this->articles;
}
}
articles document
<?php
namespace AppBundle\Document;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Dunglas\ApiBundle\Annotation\Iri;
use Symfony\Component\Validator\Constraints as Assert;
/**
#MongoDB\Document
#MongoDB\Document(collection="article")
/
class article
{
/*
#MongoDB\Id(strategy="AUTO") */
private $id;
/**
#MongoDB\ReferenceOne(targetDocument="user", inversedBy="articles") */
private $user;
/**
*/
public function setUser(userProfile $user)
{
$this->user = $user;
return $this;
}
/**
*/
public function getUser() {
return $this->user;
}
}
can any one help me to get the list of the user articles
thanks
Every class managed by API Platform needs to be marked with the #ApiPlatform\Core\Annotation\ApiResource annotation (or the equivalent in YAML or XML).
And there is no native MongoDB support yet (but this is a work in progress).
You can still add MongoDB support by yourself using a custom data provider, but if you're a newcomer to API Platform, you should try to use Doctrine ORM and follow the official tutorial first: https://api-platform.com/docs/distribution/
I'm trying to use a m:n relation, the same way as FrontEndUser is related to FrontEndUserGroup, e.g. without intermediate mm table. In my controller, I build my object, then I call $barRepository->update($barObject); to update the values of my object. However, it fails on the update function with the error:
Fatal error: Call to undefined method Cbrunet\Up\Domain\Model\Foo::getPosition() in /home/cbrunet/websites/typo3_src-6.1.1/typo3/sysext/extbase/Classes/Persistence/Generic/Backend.php on line 486
where Foo is the type of the object contained in the ObjectStorage of Bar. My understanding is that getPosition should be called on the ObjectStorage, not on the object contained into that ObjectStorage. However, I cannot figure out why this is not working in my case.
This is in TYPO3 6.1.5. Any hint would be appreciated.
The model of Bar which has a m:n relation to Foo looks like:
namespace Cbrunet\Up\Domain\Model;
class Bar extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity {
/**
* #var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\Cbrunet\Up\Domain\Model\Foo>
*/
protected $myprop;
public function __construct() {
$this->myprop = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
}
/**
* #param \TYPO3\CMS\Extbase\Persistence\ObjectStorage $myprop
* #return void
*/
public function setMyprop(\TYPO3\CMS\Extbase\Persistence\ObjectStorage $myprop) {
$this->myprop = $myprop;
}
/**
* #param \Cbrunet\Up\Domain\Model\Foo $myprop
* #return void
*/
public function addMyprop(\Cbrunet\Up\Domain\Model\Foo $myprop) {
$this->myprop->attach($myprop);
}
/**
* #param \Cbrunet\Up\Domain\Model\Foo $myprop
* #return void
*/
public function removeMyprop(\Cbrunet\Up\Domain\Model\Foo $myprop) {
$this->myprop->detach($myprop);
}
/**
* #return \TYPO3\CMS\Extbase\Persistence\ObjectStorage
*/
public function getMyprop() {
return $this->myprop;
}
}
The relevant code in my controller looks like:
/**
* action update
*
* #return void
*/
public function updateAction() {
$args = $this->request->getArgument('myargs');
foreach ($args as $k=>$val) {
$pp = $this->barRepository->findOneByAprop($k); // another prop of Bar, not illustrated in the code above.
$listepour = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
foreach ($val as $p) {
$ap = $this->fooRepository->findOneByUid(intval($p));
$listepour->attach($ap);
}
$pp->setMyprop($listepour);
$this->barRepository->update($pp); // error occurs here
}
$this->redirect('list');
}
Do you also have configured your TCA?
do you have an initStorageObjects-function in your domain model?
Also you can try to build these case with the extension-manager and compare the code.
I've got the following situation: a (Doctrine Entity) ContentCategory that is extending the DataObject class. The DataObject class has the following function, onPrePersist:
/**
* #ORM\HasLifecycleCallbacks
*/
class DataObject implements InputFilterAwareInterface
{
...
/** #ORM\PrePersist */
public function onPrePersist()
{
//using Doctrine DateTime here
$this->creation_date = new \DateTime('now');
}
The ContentCategory class needs this function aswell. When I put this function in the ContentCategory class it works just fine. Is there a way whereby, the ContentCategory class can use the same function, onPrePersist() without defining it in the class itsself?
* #ORM\HasLifecycleCallbacks()
*/
class ContentCategory extends DataObject implements InputFilterAwareInterface
{
...
}
The reason to give objects the onPrePersist function, is to set a DateTime when this object is created or any other object / entity that is extending the DataObject class.
--< Edited >--
I've currently added a construct method to the ContentCategory like this:
public function __construct() {
parent::onPrePersist();
}
In this way Doctrine executes the function onPersist when a new Entity is created. The other case is when an enttiy is being updated, with Doctrine. I'll like to set a Modified_date. In that case there will be a function like this, in the DataObject class.
/**
* #ORM\HasLifecycleCallbacks
*/
class DataObject implements InputFilterAwareInterface
{
...
/**
* #ORM\PreUpdate
*/
public function onUpdate()
{
$this->last_modified_date = new \DateTime('now');
}
The Doctrine ORM Annotation (PreUpdate) that have been added, will make sure that the function (above) will be excuted on an update statement for an object. The problem is, how to call those functions in an object which extends the DataObject
/**
* #ORM\MappedSuperclass
* #ORM\HasLifecycleCallbacks
*/
class TestimonialSuperclass
{
/**
* #ORM\PreFlush
*/
public function onPreFlush ()
{
echo 123;
}
}
/**
* #ORM\Entity
* #ORM\Table(name="testimonials")
* #ORM\HasLifecycleCallbacks
*/
class Testimonial extends TestimonialSuperclass
{
...
}
How do I inject the service manager into a Doctrine repository to allow me to retrieve the Doctrine Entity Manager?
I using the ZF2-Commons DoctrineORMModule and are trying to implement the repository example listed in the Doctrine Tutorial (bottom of tutorial in link below):
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/getting-started.html
However, I keep getting a message "Fatal error: Call to a member function get() on a non-object in C:\zendProject\zf2 ... ", which suggests that I do not have a working instance of the service locator.
My Doctrine repository looks like this:
namespace Calendar\Repository;
use Doctrine\ORM\EntityRepository,
Calendar\Entity\Appointment,
Calendar\Entity\Diary;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class ApptRepository extends EntityRepository implements ServiceLocatorAwareInterface
{
protected $services;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->services = $serviceLocator;
}
public function getServiceLocator()
{
return $this->services;
}
public function getUserApptsByDate()
{
$dql = "SELECT a FROM Appointment a";
$em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
$query = $em()->createQuery($dql);
return $query->getResult();
}
}
I then want to call this in my controller using the following pattern:
$diary = $em->getRepository('Calendar\Entity\Appointment')->getUserApptsByDate();
EDIT: The attached link suggests that I may need to convert the class to a service,
https://stackoverflow.com/a/13508799/1325365
However, if this is the best route, how would I then make my Doctrine Entity aware of the service. At the moment I include an annotation in the doc block pointing to the class.
#ORM\Entity (repositoryClass="Calendar\Repository\ApptRepository")
The way i approach things is this:
First i register a Service for each entity. This is done inside Module.php
public function getServiceConfig()
{
return array(
'factories' => array(
'my-service-entityname' => 'My\Factory\EntitynameServiceFactory',
)
);
}
Next thing would be to create the factory class src\My\Factory\EntitynameServiceFactory.php. This is the part where you inject the EntityManager into your Entity-Services (not into the entity itself, the entity doesn't need this dependency at all)
This class looks something like this:
<?php
namespace My\Factory;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\FactoryInterface;
use My\Service\EntitynameService;
class EntitynameServiceFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$service = new EntitynameService();
$service->setEntityManager($serviceLocator->get('Doctrine\ORM\EntityManager'));
return $service;
}
}
Next thing in line is to create the src\My\Service\EntitynameService.php. And this is actually the part where you create all the getter functions and stuff. Personally i extend these Services from a global DoctrineEntityService i will first give you the code for the EntitynameService now. All this does is to actually get the correct repository!
<?php
namespace My\Service;
class EntitynameService extends DoctrineEntityService
{
public function getEntityRepository()
{
if (null === $this->entityRepository) {
$this->setEntityRepository($this->getEntityManager()->getRepository('My\Entity\Entityname'));
}
return $this->entityRepository;
}
}
This part until here should be quite easy to understand (i hope), but that's not all too interesting yet. The magic is happening at the global DoctrineEntityService. And this is the code for that!
<?php
namespace My\Service;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;
use Zend\ServiceManager\ServiceManagerAwareInterface;
use Zend\ServiceManager\ServiceManager;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityRepository;
class DoctrineEntityService implements
ServiceManagerAwareInterface,
EventManagerAwareInterface
{
protected $serviceManager;
protected $eventManager;
protected $entityManager;
protected $entityRepository;
/**
* Returns all Entities
*
* #return EntityRepository
*/
public function findAll()
{
$this->getEventManager()->trigger(__FUNCTION__ . '.pre', $this, array('entities' => $entities));
$entities = $this->getEntityRepository()->findAll();
$this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array('entities' => $entities));
return $entities;
}
public function find($id) {
return $this->getEntityRepository()->find($id);
}
public function findByQuery(\Closure $query)
{
$queryBuilder = $this->getEntityRepository()->createQueryBuilder('entity');
$currentQuery = call_user_func($query, $queryBuilder);
// \Zend\Debug\Debug::dump($currentQuery->getQuery());
return $currentQuery->getQuery()->getResult();
}
/**
* Persists and Entity into the Repository
*
* #param Entity $entity
* #return Entity
*/
public function persist($entity)
{
$this->getEventManager()->trigger(__FUNCTION__ . '.pre', $this, array('entity'=>$entity));
$this->getEntityManager()->persist($entity);
$this->getEntityManager()->flush();
$this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array('entity'=>$entity));
return $entity;
}
/**
* #param \Doctrine\ORM\EntityRepository $entityRepository
* #return \Haushaltportal\Service\DoctrineEntityService
*/
public function setEntityRepository(EntityRepository $entityRepository)
{
$this->entityRepository = $entityRepository;
return $this;
}
/**
* #param EntityManager $entityManager
* #return \Haushaltportal\Service\DoctrineEntityService
*/
public function setEntityManager(EntityManager $entityManager)
{
$this->entityManager = $entityManager;
return $this;
}
/**
* #return EntityManager
*/
public function getEntityManager()
{
return $this->entityManager;
}
/**
* Inject an EventManager instance
*
* #param EventManagerInterface $eventManager
* #return \Haushaltportal\Service\DoctrineEntityService
*/
public function setEventManager(EventManagerInterface $eventManager)
{
$this->eventManager = $eventManager;
return $this;
}
/**
* Retrieve the event manager
* Lazy-loads an EventManager instance if none registered.
*
* #return EventManagerInterface
*/
public function getEventManager()
{
return $this->eventManager;
}
/**
* Set service manager
*
* #param ServiceManager $serviceManager
* #return \Haushaltportal\Service\DoctrineEntityService
*/
public function setServiceManager(ServiceManager $serviceManager)
{
$this->serviceManager = $serviceManager;
return $this;
}
/**
* Get service manager
*
* #return ServiceManager
*/
public function getServiceManager()
{
return $this->serviceManager;
}
}
So what does this do? This DoctrineEntityService pretty much is all what you globally need (to my current experience). It has the fincAll(), find($id) and the findByQuery($closure)
Your next question (hopefully) would only be "How to use this from my controller now?". It's as simple as to call your Service, that you have set up in the first step! Assume this code in your Controllers
public function someAction()
{
/** #var $entityService \my\Service\EntitynameService */
$entityService = $this->getServiceLocator()->get('my-service-entityname');
// A query that finds all stuff
$allEntities = $entityService->findAll();
// A query that finds an ID
$idEntity = $entityService->find(1);
// A query that finds entities based on a Query
$queryEntity = $entityService->findByQuery(function($queryBuilder){
/** #var $queryBuilder\Doctrine\DBAL\Query\QueryBuilder */
return $queryBuilder->orderBy('entity.somekey', 'ASC');
});
}
The function findByQuery() would expect an closure. The $queryBuilder (or however you want to name that variable, you can choose) will be an instance of \Doctrine\DBAL\Query\QueryBuilder. This will always be tied to ONE Repository though! Therefore entity.somekey the entity. will be whatever repository you are currently working with.
If you need access to the EntityManager you'd either only instantiate only the DoctrineEntityService or call the $entityService->getEntityManager() and continue from there.
I don't know if this approach is overly complex or something. When setting up a new Entity/EntityRepository, all you need to do is to add a new Factory and a new Service. Both of those are pretty much copy paste with two line change of code in each class.
I hope this has answered your question and given you some insight of how work with ZF2 can be organized.
As long as you extend the Doctrine\ORM\EntityRepository, you have immediate access to the entity manager by calling EntityRepository::getEntityManager() or the $_em attribute. The inheritence from the Doctrine\ORM\EntityRepository class allow you to do so.
Your method should now look like this:
public function getUserApptsByDate()
{
$dql = "SELECT a FROM Appointment a";
$em = $this->getEntityManager();// Or $em=$this->_em;
$query = $em()->createQuery($dql);
return $query->getResult();
}
I always keep in mind that access to my data should go from the web front (Zend MVC, Service Manager) to the persistence layer (Doctrine). My persistence (entities, repositories...) layer should not refer to the web front or neither know that it exists. If my system is doing the inverse at some level, then probably I'm doing something wrong.
Happy end of year