interface
implements
instanceOf
Interfaces closely resemble abstract classes, but cannot contain concrete
methods or properties. In order to create an interface, use the interface
keyword.
<?php
interface EntityInterface {
// ... Other constants or methods.
public function id();
public function label();
}
You can then implement an interface with another class by using the
implements
keyword. Just as concrete classes can contain additional
properties and methods to augment an abstract class, so can implementing classes contain more
properties/methods than declared in the interfaces; i.e., implementing classes need to comply with
the interface, and they can add any other thing they need.
Interfaces can also extend other interfaces.
<?php
abstract class Entity implements EntityInterface {
// ... Other constants or methods.
public function id() {
return isset($this->id) ? $this->id : NULL;
}
public function label() {
// Processing to return the label.
return $label;
}
}
You can't use variables inside of an interface, but you can use constants.
<?php
interface NodeInterface {
const NOT_PUBLISHED = 0;
const PUBLISHED = 1;
// ... Other constants or methods.
}
Those constants can be accessed via the scope resolution operator ::
inside
of an implementing class. For example:
<?php
$node->set('status', NodeInterface::PUBLISHED);
The instanceof
operator is used to find out if an object is an instantiated instance of a class. This
can be useful to make sure that a parameter or variable is a particular instance of an object before
using it. It is particularly useful to check against an interface, which is more generic than an
implementing class.
<?php
function hook_entity_presave(EntityInterface $entity) {
if ($entity instanceof ContentEntityInterface && $entity->isTranslatable()) {
$route_match = \Drupal::routeMatch();
\Drupal::service('content_translation.synchronizer')->synchronizeFields($entity, $entity->language()->getId(), $route_match->getParameter('source_langcode'));
}
}
Entities are a great place to look at interfaces. An interface allows developers wishing to create a custom entity to do so simply by adhering to the interface.
Drupal's content entities (NodeInterface
, 'CommentInterface
, UserInterface
, etc.) extend the
ContentEntityInterface
and in that way provide a unified way to access all of the content entities
and provide a consistent API for module developers.
- Create a person interface that declares the methods "work()" and "sayHi()".
- Modify the abstract class Person so it implements that interface.
- Instantiate an object from a concrete class.
- Review what errors does PHP give when a method declared in the interface is missing on the implementing class.