Demeter's Law and Return Values

According to the Law of Demeter, can you call methods for returned objects?

eg.

<?php
class O
{
    public function m($http)
    {
        $response = $http->get('http://www.google.com');
        return $response->getBody(); // violation?
    }
}
?>

$ http-> get () returns an object. Is this considered an object created / created in M? If you cannot call methods on it (according to LoD), how would you handle this situation?

+5
source share
3 answers

This is not a violation of the Law of Demeter, given :

More formally, the Demeter Law for a function requires that the method M object O can only refer to methods of the following types of objects:

  • O myself
  • M parameters
  • any objects created / created in M
  • O direct component objects
  • , O, M

$response - , M, . getBody():

$length = $response->getBody()->length;

, , " ", , .

+6

, $response , -, m, .

, $http m, , $http->get(), $response, $http, m.

" " ( ) , return $http->get('http://www.google.com')->getBody(); , . .

. - , , , $http->get(), , .

+6

One of the possibilities to solve this problem is to create an object in m (), and http-> get () to fill it with information.

class O
{
    public function m($http)
    {
        $response = new HttpResponse();
        $http->get('http://www.google.com', & $response);
        return $response->getBody(); // no violation, since we made $response ourselves.
    }
}
+1
source

All Articles