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
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
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.
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;
}
}
}