Say I have a database for storing cars data. Each row is essentially a car and I've a class that takes a row of the data and builds my car object.
I now want to build a dashboard that can tell me all the types of cars e.g.
Type Amount
BMW 12
Ford 7
I'm trying to figure out how best to design the functionality. My thoughts so far have been:
Static function call in a generic functions class. Does a count on the table. Not exactly an OOP approach so I'd prefer not to do this.
Create a class for counting cars. Not sure if this is too specific a case to warrant it's own class.
A database interface class for cars table. Perform general functions, counts, bulk updates etc. Should be static?
A counter interface class? I'm not too clear on how to build this, it's something I've kind of gleaned from reading about interfaces and decoupling?
Those are the thoughts I had. What are the suggested ways to handle this?
1 Answer 1
There are several ways to achieve your goal. Which you are going to use depends on your preferences and whether you are having an underlaying framework
or CMS
which uses a certain way. In case you are using a framework
or similiar check their coding guidelines.
Despite that I am aware of following options:
DBAL
that providesfunctions
likecount($table)
.Model
that providesfunctions
likecount
. Further the model provides functions likeget(id)
andset(...$args)
- A
RepositoryClass
that supportsCRUD
for it's model and generalmethods
used to interact with the database. For eachModel
you have aRepositoryClass
. - A
ListClass
that you can use withcount()
. Similiar toRepositoryClass
. However, the ListClass contains actually a list while the RepositoryClass returns objects or e.g. the amount of cars in your database.
I prefer the usage of either a ListClass
and or RepositoryClass
. In the following example we have a CarRepository
having a method to retrieve every available brand. The method findCarBrands
returns the class CarBrandList
which contains a list with models of type CarBrand
. As it is a list we can iterate through it and access each brand. The CarBrand
-Model has a method to get the total amount of available cars per brand. You may ask yourself where is the returned value of getTotalCars
determined. This is done in the repository class when we iterate through the sql
resultSet
or in the sql statement itself
.
<?php
/** @var CarBrandList $carBrands*/
$carBrands = $carRepository->findCarBrands();
/** @var CarBrand $carBrand*/
foreach ($carBrands as $carBrand)
{
echo $carBrand->getName() . ' | ' . $carBrand()->getTotalCars() . '<br/>';
}