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);
Note: PHP interfaces do not have constructors. When a class implements an interface, the class must implement all the interface's methods. There is one exception: if an abstract class implements an interface, it does not need to implement all the interface's methods.
You are not required to define a constructor in your class, but if you wish to pass any parameters on object construction then you need one.
PHP - The __construct Function A constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class. Notice that the construct function starts with two underscores (__)!
Multiple Constructors: More than one constructor in a single class for initializing instances are available.
While it is technically possible to add the constructor to the Interface, Interfaces should not define the constructor because that would be an implementation detail of an implementing class. An Interface should just define the public API other collaborators can call upon. That is, they should not enforce a particular implementation.
If you'd put a constructor asking for a database connection in the Interface, you'd limit the concrete classes to the dependencies in the constructor signature. If a concrete class implementing the Interface needs different (because it's saving to a Webservice) or additional (maybe a Logger) dependency you cannot make that work with your Interface.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With