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

<?php
use App\Http\Traits\ActivityLog;

trait ActivityLog {
    public function log($message, $object) {
        // Store $message and $object in database
        SomeModel::create([
            'message' => $message,
            'object_class' = get_class($object),
            'user_id' => Auth::user()->id
        ]);
    }
}

Implementation of trait in our models:

Product.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model {
	use ActivityLog;
}

Stock.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Stock {
	use ActivityLog;
}

How to access trait implemented in Models?

ProductController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Product;

class ProductController extends Controller
{
    /**
     * Store a new product.
     *
     * @param  Request  $request
     * @return Response
     */
	public function store(Request $request) {
		$product = new Product();
		$product->create($payload);
		$product->storeLog('product is created', $product);
	}
		
}

On the other hand, how to implement trait in Controller instead of Model:

StockController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Product;

class StockController extends Controller
{
	use ActivityLog;

	public function store(Request $request) {
		$product->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.

Author: Danyal
I'm skilled programmer with expertise in Vue.js/Nux.js for front-end development and PHP Laravel for back-end development. I excel in building APIs and services, and also have experience in web server setup & maintenance. My versatile skill set allows you to develop and maintain web applications effectively, from the user interface to the server-side functionality. I love coding with never ending learning attitude, thanks for visiting danya.dk