I just started learning Symfony2 (and I do not have much php experience), so my question may seem funny for someone. I'm now following Databases and Doctrine section of The Book, and my question concerns Fetching Related Objects example (I use the same code as in documentation, so I won't paste all of it here).
There is a code that fetches associated objects in this example:
public function showAction($id)
{
$product = $this->getDoctrine()->getRepository('AcmeStoreBundle:Product')->find($id);
$categoryName = $product->getCategory()->getName();
return array('product' => $product, 'category' => $categoryName);
}
When I run this controller on a Product object that has category reference set in DB everything works fine. Unfortunately, when category is null it throws "FatalErrorException: Error: Call to a member function getName() on a non-object".
I understand that this is because there is no Category object and so no Category name, but my question is what is the best way to handle such situations? I want $categoryName to return null or empty string to use in my template, just like any other not set property of Product object, but since it comes from associated object I'm stuck on this problem