2

Is there a valid Docblock tag which lets a trait know which class/interface it will be used with? e.g. (below is purely made up code).

interface Authenticatable {
    public function getId();
}

class User implements Authenticatable {
    use HasAvatar;
}

class Admin implements Authenticatable {
    use HasAvatar;
}

trait HasAvatar {
    public function getAvatarUrl() {
        return AvatarService::getAvatarUrlForId(
            $this->getId()
        );
    }
}

You can see the HasAvatar trait accesses getId() from the parent classes.

However when you're in IDE's it cannot find getId() as it doesn't belong to the trait, and there's no comment hints to say where to find this method.

Thus is there a way to tell this trait that it will be implemented in a specific way? e.g.

/**
 * @used-by \App\Interfaces\Authenticatable
 */

This will let the IDE know that it has access to everything that Authenticatable has?

Thanks

owenmelbz
  • 6,180
  • 16
  • 63
  • 113

1 Answers1

0

You can enforce the presence of that method by declaring the method as abstract inside your trait. No docblock annotation is needed then, the IDE will recognize the method and will warn you if it is missing somewhere:

trait HasAvatar {
    public function getAvatarUrl() {
        return AvatarService::getAvatarUrlForId(
            $this->getId()
        );
    }
    
    public abstract function getId();
}
thehennyy
  • 4,020
  • 1
  • 22
  • 31