So I am making a PHP website to browse my movie collection on my LAN. It has been through several iterations and now I am thinking that object-oriented is the way to go. In the current state I have several functions that get movie information from the database. So whenever I need information for a movie I have to call a few functions to get all the info and pass that to other functions to do what I want with it.
My idea for the object-oriented version is to do all these 'getinfo' functions in the constructor. So I just create a movie object and all the info is readily available use $movieobj->title
and so on.
I gave it a go and came up with this just to test it out:
class movie{
public $tite = Null;
function __construct($id, $conn){
//set title property
$sql_select = $conn->prepare("SELECT title FROM movie.title
WHERE `movieID` = {$id} LIMIT 1");
$sql_select->execute();
$sql_select->bind_result($val);
$sql_select->fetch();
$this->title = $val;
}
}
This works how I want, being able to get the movie title using:
$movie = new movie(100,$db);
echo $movie->title;
But in practice I would have a few more similar chunks of code in the constructor to get other information for the movie.
Is this the wrong way to use the constructor? Should it be more simple and then have other methods to pull this information from the database? Having a complex constructor makes other code much simpler, but is it bad practice, or could it cause problems I am not seeing?
Generally, I personally would only use the constructor to set basic property values passed in as arguments, such as the connection, keeping the constructor code itself as simple as possible; and have all the real code in other methods, such as a fetch method (e.g. getMovie()
) to actually do the database retrieval in your case, rather than direct access to the movie property (making that property private or protected).
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