I just started reading more about OOP and its design patterns and is confused with this conceptual question. I am too new that I am having second thought that the proper title should be, "when is it okay to have the constructor function in the interface?"
If interface defines the blueprint/API of your object, how do you enforce or hint the developers that the objects implementing the interface requires specific dependencies/arguments to construct the object.
Because upon researching it seems like adding the constructor function in the interface is a bad practice[1][2]?
If so, it seems like the viable solution is to have the constructor function defined in an abstract class, and make that abstract class implement the interface?
interface PostValidityInterface {
public function describe_validity();
}
abstract class PostValidityAbstract implements PostValidityInterface {
private $post_id;
private $validity_interval;
private $parser;
public function __construct( Int $post_id, \DateInterval $validity_interval ) {
$this->post_id = $post_id;
$this->validity_interval = $validity_interval;
}
public function describe_validity() {
$now = new DateTime( 'now' );
$validity = $now->add( $this->validity_interval )->format('F j Y');
return 'Post ID: ' . $this->post_id . ' is valid until ' . $validity . '.';
}
}
class PostValidity extends PostValidityAbstract {
}
$post_validity = new PostValidity(1, new \DateInterval('P1D'));
echo $post_validity->describe_validity();
// outputs:
Post ID: 1 is valid until January 1 2019.
but it feels YAGNI to me as you have 2 things to define just to describe a Class. So I wonder if this the true correct approach? or the use of interface nor abstract is to solve a far deeper problem?
when is it okay to have the constructor function in the interface?
Never. The question is: What are you trying to achieve? What's the problem to solve? Why have you added the interface to the design? Interfaces are implemented to turn objects of a given class into something else. Or in many different things.