Search code examples
laravellaravel-5.3

What is the difference between laravel method vs trait vs facade


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

method vs trait vs facade

Cheers!


Solution

  • 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.