Detailed usage examples of Trait in Laravel, laraveltrait

Source: Internet
Author: User
Tags traits

Detailed usage examples of Trait in Laravel, laraveltrait

This article describes the usage of Trait in Laravel. We will share this with you for your reference. The details are as follows:

See the definition of Trait in the PHP official manual:

Since PHP 5.4.0, PHP has implemented a method for code reuse, called traits.

Traits is a code reuse mechanism prepared for a single inheritance language similar to PHP. Trait allows developers to freely reuse method sets in independent classes in different hierarchies to reduce the restrictions of a single inheritance language. The semantics of Traits and class combination defines a way to reduce complexity and avoid typical problems related to traditional multi-inheritance and mixed classes (Mixin.

Trait is similar to a class, but it is only intended to combine functions in a fine-grained and consistent manner. Trait cannot be instantiated by itself. It adds a combination of horizontal features for traditional inheritance; that is, members of the application class do not need to inherit.

The official manual also provides two examples:

Trait usage example

<?phptrait ezcReflectionReturnInfo {  function getReturnType() { /*1*/ }  function getReturnDescription() { /*2*/ }}class ezcReflectionMethod extends ReflectionMethod {  use ezcReflectionReturnInfo;  /* ... */}class ezcReflectionFunction extends ReflectionFunction {  use ezcReflectionReturnInfo;  /* ... */}?>

Trait priority

The member inherited from the base class is overwritten by the member inserted by trait. The priority is that the members of the current class overwrite the trait method, while the trait method overwrites the inherited method.

The member inherited from the base class is overwritten by the MyHelloWorld method in the inserted SayWorld Trait. Its behavior is the same as that defined in the MyHelloWorld class. The priority is that the methods in the current class will overwrite the trait method, and the trait method overwrites the methods in the base class.

<?phpclass Base {  public function sayHello() {    echo 'Hello ';  }}trait SayWorld {  public function sayHello() {    parent::sayHello();    echo 'World!';  }}class MyHelloWorld extends Base {  use SayWorld;}$o = new MyHelloWorld();$o->sayHello();?>

The above routine will output:

Hello World!

The above content is from the PHP official manual.

Use of Trait in Laravel

Laravel uses the Trait feature extensively to improve code reusability. This article only provides an example from a Laravel project.

For example, there is a show method in a PageController. php controller:

public function show($slug){  $page = PageRepository::find($slug);  $this->checkPage($page, $slug);   return View::make('pages.show', ['page' => $page]);}

Here, the PageRepository: find () method is a Trait method. In PageRepository. php, use namespace declaration and introduction:

Namespace GrahamCampbell \ BootstrapCMS \ Repositories; use GrahamCampbell \ Credentials \ Repositories \ certificates; class PageRepository extends actrepository {use PaginateRepositoryTrait, SlugRepositoryTrait; // 800 sub-names are omitted here}

Specifically, the Trait of SlugRepositoryTrait defines the find method:

trait SlugRepositoryTrait{  /**   * Find an existing model by slug.   *   * @param string  $slug   * @param string[] $columns   *   * @return \Illuminate\Database\Eloquent\Model   */  public function find($slug, array $columns = ['*'])  {    $model = $this->model;    return $model::where('slug', '=', $slug)->first($columns);  }}

In this way, you can use Trait in control, which achieves code reuse.

Personal Understanding:

When you use Trait in a class, this class also has the attributes and methods defined in Trait. The usage scenario of Traits is that if multiple classes use the same attributes or methods, you can use Traits to conveniently add these attributes or methods to the class, instead of inheriting a class from each class, if the inherited class is vertically extended, Traits is horizontally extended to implement code reuse.

For more information about the use of Trait in PHP, see the previous article "simple use of traits in PHP".

This article

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.