Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between laravel method vs trait vs facade [closed]

In a nutshell what would be the easiest way to compare the three?

method vs trait vs facade

Cheers!

like image 659
aurawindsurfing Avatar asked Feb 05 '23 16:02

aurawindsurfing


1 Answers

They don't really compare because they're really different things.

A method is a function that belongs to a class.

class MyClass
{
     public function this_is_a_method() { }
}

A trait is a means of sharing code between classes. A trait cannot be instantiated, but rather is included into another class. Both classes and traits can define methods.

trait MyTrait
{
     public function this_is_a_method() { }
}

Now that I have this trait I can update MyClass to use this trait.

class MyClass
{
     use MyTrait;
}

You can think of traits as copy and paste. Now MyClass copies the methods defined in MyTrait so you can do this.

$class = new MyClass();
$class->this_is_a_method();

Both methods and traits are features of PHP. Facades are a feature of Laravel. Facades are simply syntactic sugar to help get services out of the container.

like image 171
jfadich Avatar answered Feb 08 '23 14:02

jfadich