Best way to handle non-existant relation


When doing relations like this …

echo $book->author->name;

If the relation between book and author no longer exists it results in a trying to get property of a non object error.

What is the best way to handle this. I am aware of doing …


But I am wondering if there is a different way which does not have to result in writing isset() etc in large areas of code.

if ($book->author != null) {



Yes that means I will have to do that check in every place where I have used a relation.

I was wondering if there was more "global" way of handling it?

If this relation coincide with a db constraint, relation must exists.

Otherwise you could use hasMany instead hasOne, that always returns a non-null value. But it is not so convenient.

class Book


  public function getAuthorName()


	return $this->author ? $this->author->name : null; 



Law of Demeter

Ok thanks guys.