Search code examples
phpoopclassinterface

PHP class constructor in interface or class


I'm having some issues thinking out a good structure to build my classes and objects. In the code below I make use of an interface to define my class methods, but I also want to pass a database connection to my constructor so the class had this connection to work with. Is it correct as I coded it below that the constructor is placed within my class and the methods in my interface?

interface IDataItem
{
    public function saveItem(Item $theItem);
}

class DataItem implements IDataItem
{
    public function __construct(Database $database) 
    { 
        $this->database = $database;
    }

    public function saveItem(Item $item) 
    {       
        //save the item
    }
}

$db = new Database(); //from a database class
$dataItem = new DataItem($db);          
$dataItem->saveItem($anItem);

Solution

  • I don't personally think you should put the constructor in the interface because you'd never create a new object by calling the constructor without being aware of which implementation you're using.

    There is a mistake in your code, the method in an interface cannot have an implementation, it needs to be just a declaration, like this

    interface IDataItem
    {
        public function saveItem($theItem);
    }