I am new to PHP and am trying to figure out the best practice with respect to binding column values to properties in a class. The column names in the database are not ideal and I would like to extract them in such a way that I can reference the object properties instead. Is the below example a reasonable approach?

class Assessment
  // @var object
  private $db;

  // @var integer
  public $id;

  // @var string
  public $name;

  public function __construct($db)
      $this->db = $db;        

  public function getById($id)
    $id = (int)$id;

    $query = $this->db->prepare("SELECT * FROM checkups WHERE checkup_id=:checkup_id");
    $query->bindValue(':checkup_id', $id, PDO::PARAM_INT);

    $assessment = $query->fetch();

    $this->id = $assessment['checkup_id'];
    $this->name = $assessment['checkup_name'];


And then used like so:

$assessment = new Assessment($db);
echo $assessment->name;

Curious if there is an additional layer of abstraction I should consider or other methods I should use for assigning the values to their properties. For example, I am not sure how I would handle fetchAll() using this method. I did note the PDO FETCH_OBJECT and similar methods but they seem only to apply if the class properties share the same name as the columns which I am trying to get away from... I am trying to avoid using a framework at the moment for learning purposes.

closed as off-topic by BobDalgleish, GlenH7 Jun 24 at 11:37

  • This question does not appear to be about software engineering within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    How would you have designed that class if you had no database and the whole app ran in memory ? What’s this class purpose ? Does this “id” property represent anything inside the domain ? You seem to be mixing two different universes here. One that’s at the extreme border of the app (database involved), and one that’s at the extreme core of the app (domain involved, since you said you wanted to control how the property are named). Get away from the the DB, implement the real logic of the app, add the DB afterwards to get actual data coming in and out. – Steve Chamaillard Jun 8 at 0:20
  • @SteveChamaillard Thank you for the input. I will put some thought into what you have said. I think you are right - it feels wrong tying the class so directly to the database... – user1392897 Jun 8 at 2:25
  • What you are doing is basically what I always would do w/ PHP. Always worked for me well. – GrandmasterB Jun 8 at 4:35

Browse other questions tagged or ask your own question.