I have two classes related to the one-to-one relationship.
class Client { ... private $info; ... public function doSomething() { if (!$this->getInfo() instanceof ClientInfo) { return false; } return $this->getInfo()->doSomething(); } ... } class ClientInfo { ... private $client; ... public function doSomething() { return 'something'; } ... }
These classes are loaded with the contents of the database using Doctrine. It works great when there is data in the database. But if there is no ClientInfo data, I get the message \ Doctrine \ ORM \ EntityNotFoundException.
Therefore, I modify the doSomething () method to take this into account.
public function doSomething() { if (!$this->getInfo() instanceof ClientInfo) { return false; } try { return $this->getInfo()->doSomething(); } catch (\Doctrine\ORM\EntityNotFoundException $e) { return false; } }
But this does not seem right to me, because it is connected with the Doctrine. I am trying to modify my unit tests to add a proxy object layout, but it also does not feel good.
Is there a better way to do this?
EDIT 1
I followed Nico Kaag's suggestion, but didn't change anything.
My constructor in my Client class is as follows:
public function __construct() { $this->info = new ClientInfo(); }
If I do var_dump from $ this-> info after retrieving my object using Doctrine, this is what I get.
object(Proxies\__CG__\MyBundle\Entity\ClientInfo)[444] public '__initializer__' => object(Closure)[461] public '__cloner__' => object(Closure)[462] public '__isInitialized__' => boolean false private 'client' (MyBundle\Entity\ClientInfo) => string '21055' (length=5) ...
EDIT 2
I finally changed what I did. I deleted the try..catch block and changed the request to retrieve objects from the database. Now I force the request to retrieve the ClientInfo object at the same time as the Client object.
That way, I can trust my test, and if I forget to request both objects at the same time, I will have an exception to remind me of this.