温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Trait怎么在Laravel中使用

发布时间:2021-01-05 15:33:39 来源:亿速云 阅读:178 作者:Leah 栏目:开发技术

Trait怎么在Laravel中使用?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

Trait用法示例

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

Trait的优先级

从基类继承的成员被 trait 插入的成员所覆盖。优先顺序是来自当前类的成员覆盖了 trait 的方法,而 trait 则覆盖了被继承的方法。

从基类继承的成员被插入的 SayWorld Trait 中的 MyHelloWorld 方法所覆盖。其行为 MyHelloWorld 类中定义的方法一致。优先顺序是当前类中的方法会覆盖 trait 方法,而 trait 方法又覆盖了基类中的方法。

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

以上例程会输出:

Hello World!

以上内容来自PHP官网手册。

Trait在Laravel中的使用

Laravel中大量使用Trait特性来提高代码的复用性,本文只是从某个Laravel项目中举个例子。

比如在一个PageController.php控制器中有个show方法:

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

这里PageRepository::find()方法就是使用的一个Trait的方法,在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子
}

其中SlugRepositoryTrait这个Trait定义了find方法:

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

关于Trait怎么在Laravel中使用问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI