Bitten by accessors

2016-11-15

Yesterday I was working on a client's project. I was trying to determine a price of a product.

The client told me that the prices were wrong. The first call gave me the correct price, but after the second call, I got a different incorrect price. This did confuse me. Also, all unit tests were succeeding.


$item = Item::make($productId);
$item->price = 300;
$item->commission = 100;

$totalPrice = $item->price + $this->commission 
// $totalPrice is 500? WTF?

After some investigation, I realized I had used an Eloquent-accessor. At the moment I implemented it was so convenient, I only had the change the code in one place. I could present a new price for products linked to affiliates in under 30 seconds. Very convenient just to add an accessor, only one change:


public function getPriceAttribute($value)
{
   return $this->price + $this->commission:
}

If I had made a method for this from the beginning, I would immediately start to look for the method, but with the accessors, it is not clear what you are doing.

From now on I will stay away from accessors even if they are convenient, but in my case, they tripped me up. At least you should not do any calculations with them, I think.

Also, you would expect to go get the same value as you just set, wouldn’t you?

Back to index


Need a simple way to do git ftp? Take a look at my app GitFTP-Deploy

Subscribe to blog updates