使用特性,接口还是两者?

Jea*_*EAU 5 php design-patterns symfony

我有一个关于在PHP中使用特性和接口的问题。

具有foobar功能的特征

<?php

trait FoobarTrait
{
  protected $foobar;

  public function setFoobar($foobar)
  {
    $this->foobar = $foobar
  }

  public function getFoobar()
  {
    return $this->foobar;
  }
}
Run Code Online (Sandbox Code Playgroud)

用于指定如何使用Trait的特定界面

<?php

interface FoobarInterface
{
    public function setFoobar($foobar);

    public function getFoobar();
}
Run Code Online (Sandbox Code Playgroud)

我想在一个类中使用foobar功能。什么是最好的方法 ?

是否有必要使用接口来实现并指定特征,或者这是诱发行为?

<?php

  class FoobarClass implements FoobarInterface
  {
    use FoobarTrait;
  }
Run Code Online (Sandbox Code Playgroud)

或这个

<?php

  class FoobarClass
  {
    use FoobarTrait;
  }
Run Code Online (Sandbox Code Playgroud)

感谢您的答复和辩论;)

t1g*_*gor 0

正如@Federkun 的评论中正确指出的那样,“这取决于”。在我看来,主要是关于你将如何使用你的FoobarClass.

  • 如果它是某种服务的实现,可以根据外部条件有多种实现(例如,考虑文件系统或 S3 来处理用户上传),我会使用FooBarInterface它,然后在其他地方使用服务。

  • 如果您只是想避免重复自己,您可以使用特征而不使用接口。abstract class AbstractFooBar { ... }甚至是封装重复代码的基础。

  • 如果您只有一种获取和设置的实现$fooBar- 只需将其全部放在同一个类中:)