_php examples of trait usages in Laravel

Source: Internet
Author: User
Tags inheritance php programming php website traits smarty template

The examples in this article describe the use of trait in laravel. Share to everyone for your reference, specific as follows:

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

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

Traits is a code reuse mechanism prepared for a single inheritance language similar to PHP. Trait to reduce the limitations of single inheritance languages, developers are free to reuse method sets in separate classes within different hierarchies. The semantics of Traits and class combinations define a way to reduce complexity and avoid typical problems associated with traditional multiple inheritance and mixed-Class (Mixin).

Trait is similar to a class, but is intended only to combine functionality in fine-grained and consistent ways. Trait cannot be instantiated by itself. It adds a combination of horizontal attributes for traditional inheritance, which means that members of the application class do not need to inherit.

The Official handbook also cites two examples:

Trait usage Examples

<?php
trait Ezcreflectionreturninfo {
  function Getreturntype () {/*1*/}
  function getreturndescription () {/*2*/}
}
class Ezcreflectionmethod extends Reflectionmethod {use
  ezcreflectionreturninfo;
  /* ... *
/}
class Ezcreflectionfunction extends Reflectionfunction {use
  ezcreflectionreturninfo;
  /* ... *
?>

Priority of trait

A member inherited from a base class is overwritten by a member that is trait inserted. Precedence is the method from which the members of the current class override the trait, while trait overrides the inherited method.

The member inherited from the base class is overwritten by the Myhelloworld method in the inserted Sayworld Trait. Its behavior is consistent with the methods defined in the Myhelloworld class. The precedence is that the method in the current class overrides the trait method, while the trait method overrides the method in the base class.

<?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 ();
? >

The above routines will output:

Hello world!

The above content from the PHP website manual.

The use of trait in Laravel

The trait feature is used extensively in Laravel to improve the reusability of code, and this article only takes 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 of using namespace declarations and introductions 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 sub} omitted here


Where slugrepositorytrait this trait defines the Find method:

Trait slugrepositorytrait
{
  /**
   * Find a 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);
  }


This can be used in the control of the trait, a good implementation of the code reuse.

Personal Understanding:

Using trait in a class is equivalent to having the properties and methods defined in trait. The traits scenario is that if multiple classes are using the same attribute or method, using traits at this time can easily add these properties or methods to the class, rather than inheriting a class for each class, and if the inheriting class is a vertical extension of a class, then traits extends a class horizontally, To achieve code reuse.

About the use of trait in PHP can also refer to the previous article "PHP Traits simple Use example"

This article turns from: Small Talk blog http://www.tantengvip.com/2015/12/laravel-trait/

More interested in laravel related content readers can view the site topics: "Laravel Framework Introduction and Advanced Course", "PHP Excellent Development Framework Summary", "Smarty Template Primer Tutorial", "PHP date and Time usage summary", "PHP object-oriented Program Design Introductory Course ", PHP string (String) Usage summary," PHP+MYSQL Database operation Introduction Tutorial "and" PHP common database Operation Skills Summary "

I hope this article will help you with your PHP programming based on the Laravel framework.

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.