Skip to content

Instantly share code, notes, and snippets.

@tiffany-taylor
Last active May 19, 2021 17:52
Show Gist options
  • Save tiffany-taylor/703e876d7eb16c243c8a55b9ad8e64b7 to your computer and use it in GitHub Desktop.
Save tiffany-taylor/703e876d7eb16c243c8a55b9ad8e64b7 to your computer and use it in GitHub Desktop.

Class design question

Question summary: I have a MySQL table jobs, it has a column field jobid. I also have a Job class which is effectively a value object, and a Job\Manager class which partly works as a data layer for Job objects. Within the Job class, there's a property id, which is the same as the MySQL column jobid. At present, renaming either the column or the property is not possible, however it was suggested that the Job class include a jobid property to make facilitating between the MySQL column and a Job object easier.

Preface: the Job class was written in a bygone era and all of its properties are stored into an associative array. Presently, this can't be improved. The Job constructor accepts an associative array as a parameter, and the constructor loops through this array, uses array_key_exists to __set the array index/value to the array of properties.

There are a few ways I can go adding jobid to this class, but I'm not sure which is best.

Within the constructor, while it loops through the array parameter to assign it to the array of properties, I can do an array index check for jobid and assign it to id.

Within the __set method, I could include a check for jobid, and assign it to id - this would require adding jobid to the array of properties, which I am unsure if that would have side effects.

The id property wouldn't go away, but it would be nice to have some kind of one-to-one relation between jobid as the MySQL column and id as the Job class property.

Code example

class Job
{
    private $properties = array(
        'id' => null,
        'title' => null,
        'app' => null,

        // Option #2: 'jobid' => null,

        // there are *a lot* more properties but I am omitting them from this example
    );

    public function __construct($config = [])
    {
        foreach ($config as $key => $value) {

            // Option #1: I could do an if statement here to check if `jobid` is present, and if so, assign it to `id` instead

            if (array_key_exists($key, $this->properties)) {
                $this->__set($key, $value);
            }
        }
    }

    public function __set($key, $value)
    {
        switch ($key) {
            // Option #2: I could do a `case 'jobid':` here
            case 'id':
                if (empty($value)) throw new \Exception("$key missing blah blah blah");

                // note that there's no break here

            case 'title':
            case 'app':
                $this->properties[$key] = trim($value);
                break;
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment