Home > Backend Development > PHP Tutorial > Detailed explanation of usage examples of Trait in Laravel, laraveltrait_PHP tutorial

Detailed explanation of usage examples of Trait in Laravel, laraveltrait_PHP tutorial

WBOY
Release: 2016-07-12 08:56:48
Original
1092 people have browsed it

Detailed examples of usage of Trait in Laravel, laraveltrait

This article explains the usage of Trait in Laravel with examples. Share it with everyone for your reference, the details are as follows:

Look at the definition of Trait in the PHP official manual:

Since PHP 5.4.0, PHP implements a method of code reuse called traits.

Traits is a code reuse mechanism for single inheritance languages ​​like PHP. Traits are designed to reduce the constraints of single-inheritance languages ​​and allow developers to freely reuse method sets in independent classes within different hierarchies. The semantics of traits and class composition define a way to reduce complexity and avoid the typical problems associated with traditional multiple inheritance and mixins.

Trait is similar to a class, but is only designed to combine functionality in a fine-grained and consistent way. Trait cannot be instantiated by itself. It adds a combination of horizontal features to traditional inheritance; that is, members of application classes do not need to be inherited.

The official manual also gives two examples:

Trait usage examples

<&#63;php
trait ezcReflectionReturnInfo {
  function getReturnType() { /*1*/ }
  function getReturnDescription() { /*2*/ }
}
class ezcReflectionMethod extends ReflectionMethod {
  use ezcReflectionReturnInfo;
  /* ... */
}
class ezcReflectionFunction extends ReflectionFunction {
  use ezcReflectionReturnInfo;
  /* ... */
}
&#63;>

Copy after login

Priority of Trait

Members inherited from the base class are overridden by members inserted by the trait. The order of precedence is that members from the current class override the trait's methods, and the trait overrides the inherited methods.

Members inherited from the base class are overridden by the MyHelloWorld method in the inserted SayWorld Trait. Its behavior is consistent with the methods defined in the MyHelloWorld class. The order of precedence is that methods in the current class override trait methods, which in turn override methods in the base class.

<&#63;php
class 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();
&#63;>

Copy after login

The above routine will output:

Hello World!

Copy after login

The above content is from the PHP official website manual.

Using Trait in Laravel

Trait features are widely used in Laravel to improve code reusability. This article is just an example from a certain 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]);
}

Copy after login

The PageRepository::find() method here is a Trait method used. Use namespace declaration and introduction in PageRepository.php:

namespace GrahamCampbell\BootstrapCMS\Repositories;
use GrahamCampbell\Credentials\Repositories\AbstractRepository;
use GrahamCampbell\Credentials\Repositories\PaginateRepositoryTrait;
use GrahamCampbell\Credentials\Repositories\SlugRepositoryTrait;
class PageRepository extends AbstractRepository
{
  use PaginateRepositoryTrait, SlugRepositoryTrait;
  // 此处省略800子
}

Copy after login

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

Copy after login

In this way, Trait can be used in the control, which realizes code reuse very well.

Personal understanding:

Using Trait in a class is equivalent to the class also having the attributes and methods defined in Trait. The usage scenario of Traits is if multiple classes use the same attributes or methods. At this time, using Traits can easily add these attributes or methods to the class without having to inherit a class for each class. If the inherited class is If you extend a class vertically, traits extend a class horizontally to achieve code reuse.

For information on the use of Traits in PHP, please refer to the previous article "Simple Usage Examples of Traits in PHP"

This article is reproduced from: Xiaotan Blog http://www.tantengvip.com/2015/12/laravel-trait/

Readers who are interested in more information about Laravel can check out the special topics on this site: "Introduction and Advanced Tutorial on Laravel Framework", "Summary of PHP Excellent Development Framework", "Basic Tutorial on Getting Started with Smarty Templates", "php Date and Time" Usage Summary", "php object-oriented programming introductory tutorial", "php string (string) usage summary", "php mysql database operation introductory tutorial" and "php common database operation skills summary"

I hope this article will be helpful to everyone’s PHP program design based on the Laravel framework.

Articles you may be interested in:

  • PHP's Laravel framework combined with MySQL and Redis database deployment
  • Using message queue queue and asynchronous queue in PHP's Laravel framework Method
  • Laravel executes the migrate command prompt: No such file or directory solution
  • Detailed explanation of the steps to register Facades in Laravel
  • Laravel method to implement automatic dependency injection of constructors
  • How Laravel uses Caching to cache data to reduce database query pressure
  • Making an APP interface (API) based on laravel
  • Detailed explanation of the use of Eloquent object-relational mapping in PHP's Laravel framework
  • A summary of Laravel framework database CURD operations and coherent operations
  • In-depth analysis of event operations in PHP's Laravel framework

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1111346.htmlTechArticleDetailed explanation of usage examples of Trait in Laravel, laraveltrait This article explains the usage of Trait in Laravel with examples. Share it with everyone for your reference, the details are as follows: Take a look at the PHP official manual's definition of Trait...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template