2

I'm new in Laravel, I got a quest about helper (psr4 autoload class) & trait

I create a autoload class, connect to api and do various things.

My question is what's different between this and trait?

I can use trait to do all the same things

Benjamin W
  • 2,658
  • 7
  • 26
  • 48

2 Answers2

2

A trait is used to create small items of re-usable code which can be shared between multiple classes. They exist generally because you can only extend one class at at time in PHP. You use a trait, if for instance, you had a function or set of functions which would be useful in more than one class.

Laravel uses Composer which uses the PSR-4 standard of autoloading (amongst others), this simply means that you don't have to worry about using require, include or anything else to make the contents of a file available.

edcs
  • 3,847
  • 2
  • 33
  • 56
1

A trait is a specific set of re-usable functionality which you can attach you whatever entity only with the limitation that it needs to have no dependencies from the class you're using the trait from.

The helper file usually contains global functions that can be useful everywhere, like comparison functions, or even just shortcuts to IoC injected classes.

if (! function_exists('clock'))
{
    function clock()
    {
        if (class_exists(Clock::class)) {
            return app()['clock'];
        } else {
            return false;
        }
    }
}
GiamPy
  • 3,543
  • 3
  • 30
  • 51
  • do u think is it good idea create a trait and put it into autoload? – Benjamin W Feb 08 '17 at 10:23
  • You /need/ to put it into the PSR-4 autoloader, otherwise you're not going to be able to use it. Actually, if you follow PSR-4 it should automatically be loaded. – GiamPy Feb 08 '17 at 10:24
  • i just did a test, i carete a trait foo without add it into autoload, and inside of my controller, i use foo, it still work – Benjamin W Feb 08 '17 at 10:26
  • Because PSR-4 automatically injects it, depending on which namespace you use. http://www.php-fig.org/psr/psr-4/ – GiamPy Feb 08 '17 at 10:26
  • so do i still add autoload file into it, or not? ok i got it, if i add it into auto load, i dont need to worry about namespace – Benjamin W Feb 08 '17 at 10:27
  • By "putting it in the autoload" you mean the composer.json? – GiamPy Feb 08 '17 at 10:29
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/135163/discussion-between-benjamin-w-and-giampy). – Benjamin W Feb 08 '17 at 10:30