Talking to the Methods Not the Properties

Posted: 2015-08-12 10:14:48

Just a team related style guide item.

When talking to properties in a class talk via a getter.

<?php

class Foo {

 protected $client;


  function bar()
  {
    return $this->client->getAll();
  }

}

Would then become

<?php

class Foo {

 protected $client;


  function bar()
  {
    return $this->getClient->getAll();
  }

  function getClient()
  {
    return $this->client;
  }

}

There are a few reasons for this

  • Consistent style for the team
  • Changes to that property can be done in one place. So if we have to for example alter it before it is used then we can do it here.
  • PHPUnit Mockery can mock both but mocking a Method over a Property is another style I prefer.
  • Easier to have your IDE see all the places that is being used.
  • Instantiate on use

Instantiate on Use

When writing a package/libraries that does not have dependency injection and I do not want to make the __constructor too busy I will do this instead.

<?php

class Foo {

 protected $client;


  function bar()
  {
    return $this->getClient->getAll();
  }

  function getClient()
  {
    if($this->client == null)
      $this->setClient();

    return $this->client;
  }

  function setClient($client = null)
  {
    if($client == null)
      $client = new Client();

    $this->client = $client;
    return $this;
  }

}

This makes it simple to mock during testing and simple to instantiate as needed.


Tags:

team laravel php