Roeland
Roeland

Reputation: 3858

Should my Doctrine entities implement interfaces?

I have been told I should be coding my Doctrine POPO entities to implement an interface. My understanding is that it is best practice to code to interfaces.

Could someone provide me with some benefits to having my Doctrine entities implementing an interface. I want to make sure I understand the benefits of doing this abstraction before I spend the time writing all my entities implementing interfaces. Below is an example (do note the Doctrine annotations are note included for simplicity):

<?php
class User implements UserInterface()
{
    function getName() {
        return $this->name;
    }

    function setName($name) {
        $this->name = $name;
    }

    function addPermission(Permission $permission) {
        $this->permissions[] = $permission;
    }
}

interface UserInterface()
{
    function getName();

    function setName($name);

    function addPermission(Permission $permission);
}

Upvotes: 3

Views: 6289

Answers (1)

Twifty
Twifty

Reputation: 3378

I will answer this within the frame of database Entities only.

Generally speaking, entities need not implement an interface. But, there are exceptions.

  1. When passing your entities to 3rd party code.
    As with the UserInterface, some 3rd party code expects to be able to gather data about a certain object. The users login name and email as is the case with Symfony.

  2. When distributing your code as 3rd party.
    An example would be RoleInterface. Your bundle may manage entities, FOSUserBundle for example, but end users may not like your implementation or even not want them stored in a database. Using an interface allows us to re-implement existing code without breaking things. (Your bundle should be checking for interfaces and not classes).

  3. When things may change in the future.
    Hard coding objects essentially ties them to the code. You mention doctrine but what if in the future you wanted to migrate to propel? Like point 2 above, interfaces make the transition easier.

  4. Testing
    It's much easier to create mock objects when only an implementation of an interface is required.

  5. Team development
    Like point 4 above. A class may change during its creation which often leads to updating method calls throughout your code. This leads to problems when there are multiple developers. Having a common interface forces each developer to follow the rules governed by the interface.

Upvotes: 5

Related Questions