I've recently started using PHP OOP, and I'm now working on an application where different company representatives can create job offers that candidates can look at.
I have a variety of objects for most entities such as Company
, Candidate
, Offer
.
The problem that I have is that these objects all need to be stored in a database, and I need methods to retrieve the information, create the objects and return them. Since it does not make sense - at least to me with my limited experience in OOP - for an object to have access to the database and be able to fetch itself, I'm using a Database
class for each of my main objects that are stored in the database : CompanyDatabase
, CandidateDatabase
, OfferDatabase
.
Each of the aforementionned classes have static
methods that retrieve one or multiple "objects" from the database - this is a three-step process, they fetch the data, create the objects and return them.
Here's an example of such a xDatabase
class (where x
is the name of the class)
class CompanyDatabase{
public static function getFromID($id)
{
$company = Database::query("SELECT * FROM companies WHERE id = ?", [$id]);
return new Company($company->id, $company->name);
}
public static function save($company)
{
Database::update("UPDATE compagnies SET name = ? WHERE id = ?", [$company->name, $company-id]);
}
}
And the Company
class in this case :
class Company{
public $id;
public $name;
public function __construct($id, $name)
{
$this->id = $id;
$this->name = $name;
}
}
I've excluded some code, like the validation to check wether or not data was fetched from the database, because I felt it wasn't relevant to my concerns here.
Is this the proper way of doing it? I end up with two seperate classes for just about every object type that I have, and I'm wondering if I'm doing something wrong and should rather keep everything in one class.