Tuesday, November 10, 2009

The Law of Demeter

Today I've read a very interesting blog post. What brought my attention is thing which bothered me for quite a long time in the past, I mean this:

Most of the Symfony projects I’ve worked on are rife with lines of code like this (in the actions):

$this->getUser()->getGuardUser()->getProfile()->getEmail()

To conform to the above ideals (The Law Of Demeter) the code should be re-written as:

$this->getUser()->getEmail()

My solution for that problem is using magic method __call() in myUser class:

public function __call($method, $arguments)
 { 
  if(is_array($arguments))
  {
   return call_user_func_array(array($this->getGuardUser()->getProfile(), $method), $arguments);
  }
  else
  {
   return $this->getGuardUser()->getProfile()->$method();
  }
 }

It's possible because both tables have 1:1 relationship. This way we basically merge both objects and don't have to create dozens of "shortcut" methods.