5

When you want to insert an Entity you do this:

$user = new User();
$user->setEmail('john@doe.com');

$em->persist($user);
$em->flush();

But what if I want to create an article which can have one User;

Currently, I need to do:

$user = $em->getRepository('User')->find($id);
$article->setUser($user);

This is because of the relationship, Doctrine 2 asks for an User entity.

However, I can't "mock" an User object, because I don't want the id be set manually, therefore I can't do:

$user = new User();
$user->setId(45);

Am I wrong about this behavior, how do you do?

It can be performance matter to load the User entity just to set the relationship, even with a cache, which cannot be always an option, especially for an update.

JohnT
  • 967
  • 2
  • 16
  • 30

2 Answers2

10

If you don't have a managed User entity handy, what you want is a reference proxy, which the EM will be happy to give you:

<?php
$article = new Entity\Article();
$article->setTitle('Reference Proxies Rule');
$article->setBody('...');
$article->setUser($em->getReference('Entity\User',45));
$em->persist($article);
$em->flush();
timdev
  • 61,857
  • 6
  • 82
  • 92
  • Lol Tim, again this elusive `getReference()` function saves the day. BTW - Typo in your code `$em()`. – Cobby May 16 '11 at 13:36
  • @Cobby - it seems like the #1 clearly-documented-but-often-overlooked feature. Maybe we've found a decent use-case for after all. Thanks for the typofix. – timdev May 16 '11 at 17:27
-1

Why does your Article require a User to have an Id in the first place? You should be able to unit testing your Entities without the EntityManager, if you can't then you're probably doing something wrong. Then when you do functional unit tests it's as simple as this.

I recommend you watch Unit Testing Doctrine 2 Entities from Zend Casts.

Cobby
  • 5,273
  • 4
  • 28
  • 41
  • 1
    Well, that's not the problem, either existing User or not, if I want to update my Article with an existing User, I need to first fetch the User entity before, else how could Doctrine2 know about the user if my User doesn't have an id? my Article absolutely doesn't need to have an User to be valid. I'm just saying I can't allow an entity to set its own id and therefore mock an User object. – JohnT May 15 '11 at 23:01
  • Btw, thank for the link but I already know this screencast but I didn't find it really helpful concerning Entities Unit Testing. – JohnT May 15 '11 at 23:05