Is there a way to extend a trait in PHP?

PhpLaravelTraitsPhp 7

Php Problem Overview


I want to use functionality of an existing trait and create my own trait on top of it only to later apply it on classes.

I want to extend Laravel SoftDeletes trait to make SaveWithHistory function, so it will create a copy of a record as a deleted record. I also want to extend it with record_made_by_user_id field.

Php Solutions


Solution 1 - Php

Yes, there is. You just have to define new trait like this:

trait MySoftDeletes 
{
    use SoftDeletes {
        SoftDeletes::saveWithHistory as parentSaveWithHistory;
    }

    public function saveWithHistory() {
        $this->parentSaveWithHistory();

        //your implementation
    }
}

Solution 2 - Php

I have different approach. ParentSaveWithHistory is still applicable method in this trait so at least should be defined as private.

trait MySoftDeletes
{
    use SoftDeletes {
        saveWithHistory as private parentSaveWithHistory; 
    }

    public function saveWithHistory()
    {
        $this->parentSaveWithHistory();
    }
}

Consider also 'overriding' methods in traits:

use SoftDeletes, MySoftDeletes {
    MySoftDeletes::saveWithHistory insteadof SoftDeletes;
}

This code uses method saveWithHistory from MySoftDeletes, even if it exists in SoftDeletes.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYevgeniy AfanasyevView Question on Stackoverflow
Solution 1 - PhpFilip KoblańskiView Answer on Stackoverflow
Solution 2 - PhpJsowaView Answer on Stackoverflow