5

I have a question about using Trait and Interfaces in PHP.

A trait with foobar function

<?php

trait FoobarTrait
{
  protected $foobar;

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

  public function getFoobar()
  {
    return $this->foobar;
  }
}

The specific Interface to specify how to use Trait

<?php

interface FoobarInterface
{
    public function setFoobar($foobar);

    public function getFoobar();
}

I want use foobar feature in a class. What is the best way ?

It is necessary to implements with an interface and specify trait or it is an induced behavior ?

<?php

  class FoobarClass implements FoobarInterface
  {
    use FoobarTrait;
  }

Or this

<?php

  class FoobarClass
  {
    use FoobarTrait;
  }

Thank's for your reply and debate ;)

  • 2
    With the interface, you can test your object with instanceof and do some stuff in this case – doydoy44 Oct 25 '16 at 12:24
  • 3
    The answer to "_What is the best way?_" is always "_it depends_" – Federkun Oct 25 '16 at 12:30
  • 3
    [This answer](http://stackoverflow.com/a/9205347/4681654) could be helpful – simon Oct 25 '16 at 12:43
  • 2
    instanceof works with traits as well as with interfaces, but you can't type hint traits. Therefor, if you are absolutely positive you want to use traits, I'd recommend pairing them with interfaces as I covered it [here](http://stackoverflow.com/a/36516565/4782314). – Kuba Birecki Oct 25 '16 at 13:37
  • 1
    Would always implement the interface. The traut is just language assistant copy and paste. If you have a functionality that can be segregated then the interface is the eay to use. – Maximilian Ruta Nov 21 '18 at 21:57
  • 1
    Any class that implement that interface should use the trait or define these methods itself. If you have multiple classes that define the same methods, you can use traits to keep it DRY. Otherwise using only the trait doesn't force other sibling classes to have these methods. The interface forces it, the trait gives it. – Taha Paksu May 21 '19 at 13:03

1 Answers1

0

As it was correctly stated in the comments by @Federkun, "it depends". In my opinion mostly on how are you about to use your FoobarClass.

  • If it's an implementation of some kind of service that can have multiple implementations depending on external conditions (consider file system or S3 for handling user uploads, as an example), I would use FooBarInterface as I can then type-hint it in other places using the service.

  • If you wish to just avoid repeating yourself, you could use a trait and no interfaces. Or even a base abstract class AbstractFooBar { ... } to encapsulate the repeating code.

  • If you only have one implementation for getting and setting $fooBar - just put it all in the same class :)

Dharman
  • 30,962
  • 25
  • 85
  • 135
t1gor
  • 1,244
  • 12
  • 25