0 reply: The laravel framework uses traits in large quantities. A few examples are provided.
Trait is used in Eloquent. Then, during model initialization, there is a boot method that will automatically determine which trait is used for the current class. Then an array is obtained. The program will traverse this array to find if there is any method that meets the "bootTraitName" (defined in trait), and execute it if there is one.
Eloquent uses this method to perform automatic loading of events when initializing a model. In its built-in functions, softDelete does this. Simply put, the model that uses softDelete will automatically execute bootSoftDelete during boot, and all queries of the model will be added to a process for judging the deleted_at field by default, to retrieve only undeleted data.
This method provides a lot of convenience (IMAGINE loading a cachable trait, each time a boot is performed, an event is added to the model. Once a record is modified, automatically generate a cache ).
Trait is also frequently used in other laravel scenarios. For example, the User model is a Laravel driver used for identity authentication. Methods related to identity authentication are loaded using a trait. Laravel's self-contained AuthController also makes password retrieval and other features into trait. In this way, when we need to change another controller for verification driver, we will automatically get the relevant method by writing a line of use code.
Laravel uses trait. Another typical example is dispatch. This trait is mainly called in laravel's controller. In this way, laravel controllers can use $ this-> dispatch () to directly schedule tasks. In addition, any class that uses the DispatchJob's trait can use the same scheduling method (in fact, the app () gets a dispatch Singleton)
I wonder whether the above answers satisfy the subject. I used traits as the model. I wonder if there is any problem?
I have not done this yet.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.