Published
danyal.dk
Published
Traits in PHP and Laravel?
This is a fact that in PHP you can only have single inheritance. That means a class can inherit from only one other class. For example if a class needs to inherit more than one methods from different classes in order to prevent duplication of the code, it can’t extend multiple classes.
It is not possible in versions < PHP 5.4, but in PHP 5.4 a new feature was added known as Traits and is used effectively in Laravel.
I have created a Traits folder in my app/Http in Laravel project with a Trait called ActivityLog.php. Let’s take a look at very simple example how to implement Traits:
ActivityLog.php
$message,
'object_class' = get_class($object),
'user_id' => Auth::user()->id
]);
}
}
Implementation of trait in our models:
Product.php
Stock.php
How to access trait implemented in Models?
ProductController.php
create($payload);
$product->storeLog('product is created', $product);
}
}
On the other hand, how to implement trait in Controller instead of Model:
StockController.php
update($payload);
$this->storeLog('product is updated', $product);
}
}
Get Gist of code examples here.
Quite simple, isn’t it. I never used this feature of PHP before I started to code in Laravel. Really a useful feature to reduce code duplication.