Scout APM is PHP application performance monitoring designed for developers. With tracing logic that ties issues back to the line of code causing them, you can pinpoint n+1 queries, memory leaks, and other abnormalities in real time so you can knock them out and get back to building a great product. Start your free 14-day trial today and get the performance insight you need in less than 4 minutes.

How to call an overridden trait function

Original – by Freek Van der Herten – 3 minute read

Traits are a wonderful thing in PHP. You can use them to reduce code duplication by putting common functions in a trait and apply them to all classes where those functions are needed. I also sometimes use traits to break up a large function in multiple single-use traits.

In this post, I'd like to show you how you can override a trait function and call it from the overriding function.

Overriding a trait function

Let's create a simple trait and use it in a class.

trait MyTrait
{
   public function sayHi()
   {	
      echo 'trait says hi';
   }
}

class MyClass
{
   use MyTrait;
}

Executing (new MyClass)->sayHi(); will output "trait says hi".

The trait function can be overridden simply by defining a function with the same name in the class.

class MyClass
{
   use MyTrait;
   
   public function sayHi()
   {	
      echo 'class says hi';
   }
}

Now (new MyClass)->sayHi(); will output "class says hi".

Calling the trait implementation from inside the overridden function

You probably don't need this every day, but here's how you can call the sayHi implementation from the trait inside the sayHi function from the class.

class MyClass
{
   use MyTrait {
      sayHi as protected sayHiFromTrait;
   }
	
   public function sayHi()
   {	
      $this->sayHiFromTrait();
		
      echo ' and class says hi';
   }
}

Now (new MyClass)->sayHi(); will output "trait says hi and class says hi".

An example where I needed this

I'm currently working on Media Library Pro. This package will provide, next to Vue and React components, a couple Livewire powered components that make it easy to upload files to the media library.

Under the hood it will use Livewire's upload capabilities. To use Livewire's upload functionalities, you need to apply a trait called WithFileUploads. Out of the box, Livewire handles upload errors too. This is done inside the uploadErrored function of the trait.

The collection component of media library pro can be used to administer files inside a media library collection.

Here's how the collection component looks like by default.

collection

If you try to add a file to the collection that is too big, an error message is displayed at the top.

collection

If you want to replace a file in the collection, you can drag a file on top of a row. If the file isn't accepted, an error message is displayed on the row.

item

To achieve this, the component still relies on the uploadErrored implementation inside of the Livewire's WithFileUploads trait. The implementation will try a ValidationException. In our component, we catch that exception and perform the necessary logic to display the error message at the right place. Here's the relevant code inside our component.

namespace Spatie\MediaLibraryPro\Http\Livewire;

use Illuminate\Validation\ValidationException;
use Livewire\Component;
use Livewire\WithFileUploads;

class LivewireUploaderComponent extends Component
{
   use WithFileUploads {
      uploadErrored as protected uploadErroredTrait;
   }
      
   // ...
   
    public function uploadErrored($name, $errorsInJson, $isMultiple)
    {
        try {
            $this->uploadErroredTrait($name, $errorsInJson, $isMultiple);
        } catch (ValidationException $exception) {
            $uploadError = $exception->validator->errors()->first();

            $this->replacingMedia()
                ? $this->emit('showItemUploadError', $this->uuid, $uploadError)
                : $this->emitUp('showListErrorMessage', $uploadError);
        }
    }
}

Closing thoughts

I hope you enjoyed this little explanation of how you can call overridden trait methods. To stay in the loop of media library pro, subscribe to the mailing list at medialibrary.pro

Stay up to date with all things Laravel, PHP, and JavaScript.

Follow me on Twitter. I regularly tweet out programming tips, and what I myself have learned in ongoing projects.

Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.

Comments

Webmentions

Luis Escobar Bravo liked on 22nd September 2020
Roman Pronskiy liked on 22nd September 2020
Roman Pronskiy liked on 22nd September 2020
Haz liked on 22nd September 2020
Momen Albelbeisi retweeted on 22nd September 2020
Sebastian Müller liked on 22nd September 2020
Ashish Dhamala replied on 22nd September 2020
🤯🤯🤯
Luigi Cruz liked on 22nd September 2020
Francisco Junior liked on 22nd September 2020
Khai Rahman liked on 22nd September 2020
Neil Carlo Faisan Sucuangco liked on 22nd September 2020
James 🚀 liked on 21st September 2020
Tyroga liked on 21st September 2020
Paulund liked on 21st September 2020
Jamy Libouton liked on 21st September 2020
RR liked on 21st September 2020
Jānis Lācis liked on 21st September 2020
Wyatt liked on 21st September 2020
David Couto liked on 21st September 2020
Aryeh Feld replied on 21st September 2020
Cheap car.jpeg Lol 😂 🤣 😅
ahmed abdelaal liked on 21st September 2020
Amit Merchant liked on 21st September 2020
José Cage liked on 21st September 2020
Willan Correia liked on 21st September 2020
Willan Correia liked on 21st September 2020
José Cage liked on 21st September 2020
Aryeh Feld liked on 21st September 2020
Parvej Ahammad liked on 21st September 2020
Squarem Limited liked on 21st September 2020
Spatie retweeted on 21st September 2020
Simpledev liked on 21st September 2020
Tiago Rodrigues retweeted on 21st September 2020
Wyatt liked on 21st September 2020
Tiago Rodrigues liked on 21st September 2020
Freek Van der Herten replied on 21st September 2020
Fixed, thanks for reporting!
Matthias Ludwig liked on 21st September 2020
Matthias Ludwig replied on 21st September 2020
Thx Freek! :-) Code indent is a little bit broken here
/dev/prabakaran liked on 21st September 2020
Petar Djurich liked on 21st September 2020
/dev/prabakaran replied on 21st September 2020
Those filenames 😅😅😅
Jess Archer replied on 21st September 2020
Thanks! I wanted this today when overriding defaultProfilePhotoUrl() on the HasProfilePhoto trait in Jetstream. I switched it to use unavatar, but fall back to the ui-avatars.com URL from the trait. I was too lazy to look this up so I just copy/pasted the URL 😔
Ivan replied on 21st September 2020
😂 that cheap/expensive car images
Niels liked on 21st September 2020
Steve Bauman liked on 21st September 2020
Nick Ciske liked on 21st September 2020
Miguel Orellana liked on 21st September 2020
ali ali liked on 21st September 2020
ali ali liked on 21st September 2020
JOHN DOE liked on 21st September 2020
JOHN DOE liked on 21st September 2020
Jake Dohm liked on 21st September 2020
Nanderson Castro retweeted on 21st September 2020
Nanderson Castro liked on 21st September 2020
Haneef Ansari 🍭 liked on 21st September 2020
. liked on 21st September 2020
Fortez Fabrice liked on 21st September 2020
Robin Dirksen liked on 21st September 2020
Hardik Shah liked on 21st September 2020
Omar Andrés Barbosa Ortiz liked on 21st September 2020
Ruslan liked on 21st September 2020
Tauseef shah liked on 21st September 2020
Mark Andrew Kato liked on 21st September 2020
Peter Brinck 🤘 liked on 21st September 2020
Guill Lo liked on 21st September 2020
Santosh Khanal liked on 21st September 2020
M. Vug liked on 21st September 2020
spiritBreaker retweeted on 21st September 2020
mahmoud samy liked on 21st September 2020
Mark Topper liked on 21st September 2020
Parthasarathi G K liked on 21st September 2020
Akinyosoye Gabriel Oluwafemi retweeted on 21st September 2020
Tauseef shah liked on 21st September 2020
Thijs van den Anker liked on 21st September 2020
Akinyosoye Gabriel Oluwafemi liked on 21st September 2020
Ruslan liked on 21st September 2020
Borislav Borissov liked on 21st September 2020
Momen Albelbeisi retweeted on 21st September 2020
Hamza Makraz retweeted on 21st September 2020
Krom Ayε dε retweeted on 21st September 2020
Hamza Makraz liked on 21st September 2020
Mozammil liked on 21st September 2020
faizee liked on 21st September 2020
Krom Ayε dε liked on 21st September 2020
Robin Dirksen liked on 21st September 2020
Haz liked on 21st September 2020
Sander van Hooft replied on 21st September 2020
Wow. Is there some official documentation on this? Can *not* find it here: php.net/manual/en/lang…
maesbn 🌲 liked on 21st September 2020