103

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.

Yevgeniy Afanasyev
  • 37,872
  • 26
  • 173
  • 191
  • 2
    Possible duplicate of [Extend Traits with Classes in PHP?](http://stackoverflow.com/questions/10056520/extend-traits-with-classes-in-php) – Mihai Matei Oct 28 '16 at 06:20
  • 2
    https://stackoverflow.com/a/37687295/470749 is a good answer. – Ryan Nov 13 '18 at 17:55

2 Answers2

181

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
    }
}
molerat
  • 946
  • 4
  • 15
  • 43
Filip Koblański
  • 9,718
  • 4
  • 31
  • 36
  • Just for reference, to searchers, here is further information: https://www.php.net/manual/en/language.namespaces.importing.php – That Realty Programmer Guy Aug 20 '19 at 21:18
  • In this context, you might find the following resource helpful: https://stackoverflow.com/questions/39820753/how-does-insteadof-keyword-in-a-trait-work – J. D. Oct 16 '19 at 10:57
  • https://stackoverflow.com/a/37687295/470749 shows another example of extending traits. – Ryan Oct 18 '19 at 21:41
13

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.

Jsowa
  • 9,104
  • 5
  • 56
  • 60