I found some projects that all public methods are not declared in the interface while the interface only used once.
Like this the class and the interface. transform
method is not declared in the interface.
AFAIK we use interfaces to allow the computer to enforce certain properties on an object (class).
So should we add all public methods in the interface when there is only one implementation of that interface?
That depends on what your interface is expressing. There doesn't need to be a 1:1 correlation between an interface and a class, otherwise the distinction of interfaces and classes would be largely pointless.
You define interfaces abstractly to describe expectations an object needs to fulfil. E.g.:
interface Foo {
public function bar();
}
function baz(Foo $foo) {
$foo->bar();
}
This describes a function baz
which requires an argument $foo
which implements at least one method bar()
. To fulfil this requirement, you need to have a class that implements Foo
. That class may additionally implement other interfaces or implement more methods than just that.
class ConcreteFoo implements Foo, Bar, Baz, Countable, ArrayAccess {
public function bar() { ... }
public function ham() { ... }
...
}
This class fulfils the expectation of interface Foo
, in addition to many other things. That doesn't need to concern interface Foo
nor function baz
. This is called interface segregation.
So, no, an interface does not necessarily express each and every method of a class that implements it.
You don't need interfaces for all your classes, but many people think it is a good idea to put interfaces between different layers of the application or between different logical blocks of your application.
So for example if your application accessess a database it is a good idea to put an interface between the database and the rest of the application, so you can easily use another database without changing the rest of the application.
The example in your application is a repository, there is a pattern for that:
Repository
Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.
If you have different logical blocks of source code in different directories it is also a good idea to put interfaces between them, you might decide at one point to put one part on a different server. There is nice tool to define boundaries and check that you don't break them: deptrac
Once you define the rules and run deptrac it will create an image like this: