In laravel, traits are a code reuse mechanism prepared for single inheritance languages like PHP. Traits are used to reduce the restrictions of single inheritance languages and enable developers to freely work within different hierarchies. Reusing methods in independent classes can be simply understood as an implementation method to facilitate code reuse.
#The operating environment of this article: Windows 10 system, Laravel version 6, Dell G3 computer.
What is trait in laravel
Trait is a code reuse mechanism prepared for single inheritance languages like PHP. Traits are designed to reduce the limitations of single-inheritance languages and allow developers to freely reuse methods in independent classes within different hierarchies. The semantics of Trait and Class composition define a way to reduce complexity and avoid the typical problems associated with traditional multiple inheritance and Mixin classes.
First we need to know how to define a Trait. The keyword used is trait
namespace App\Traits; trait HasCreator { }
Call
namespace App; use App\Traits\HasCreator; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Post extends Model { use HasCreator, SoftDeletes; protected $fillable = ['title', 'user_id']; protected static function boot() { parent::boot(); self::hasCreator(); } }
to merge the methods in the Trait into the model. Just use it and then call it as you declared.
There is actually a priority here: calling class>Trait> parent class
trait SoftDeletes { protected $forceDeleting = false; public static function bootSoftDeletes() { ... } public function forceDelete() { ... } }
trait can define properties and methods
Method name in trait: hasCreator () is changed to bootHasCreator and will be called by default when using
Related recommendations: The latest five Laravel video tutorials
The above is the detailed content of What is trait in laravel. For more information, please follow other related articles on the PHP Chinese website!