In the pages so far, I have had used one connection class and one class to hold the logic for the page. However, I now have a page where I need to use multiple classes based on different scenarios that may happen.
This is what I have been able to make work, but it seems like bad practice. I’ve searched around but can’t find a solution. So my question is, what is a better way of what I’m trying to do.
<?php
require 'class/connect.php';
$db = new Connect();
require 'class/normal-page.php';
require 'class/get-page.php';
?>
<?php if (!isset($_GET['id'])) { ?>
<?php $normalpage = new NormalPage($db); ?>
<?php
} else {
$id = $_GET["id"];
$getpage = new Getpage($id, $db);
?>
<h1><?php echo $getpage->getTitle(); ?></h1>
<p><?php echo $getpage->getDescription(); ?></p>
<?php } ?>
class Normalpage {
function __construct($db) {
$query = 'SELECT something FROM table';
$result = $db->query($query);
}
}
Hope that’s enough info to make sense. So in short, I include the connect class and use the variable in both other classes.
This is a proper way of dealing with the database object. In fact, it is called the dependency injection design pattern, and is actually quite common. You might want to consider saving the constructor parameter
$dbto a member variable so other class methods may access the database via something like$this->dbif you declare the member variable asprivate $db;.However, you might want to consider the factory design pattern, as it will help organize the classes for your pages. See this example from the above link: