I'm not entirely sure the best way to handle a status field that relates to integers in a database table within a class.
Say we have the following:
$status = array(1 => 'Active', 2 => 'Inactive', 3 => 'Cancelled');
I'm thinking for clarity in the system, I want class constants and a getter for retrieving the status in an associative array, and so the class uses something better defined than "1" or "2".
class User {
const USER_STATUS_ACTIVE = 1;
const USER_STATUS_INACTIVE = 2;
const USER_STATUS_CANCELLED = 3;
public function getStatusList() {
return array(User::USER_STATUS_ACTIVE => 'Active',User::USER_STATUS_INACTIVE => 'Inactive',User::USER_STATUS_ACTIVE => 'USER_STATUS_CANCELLED');
}
}
This then allows setting the status using the constants with:
class User {
private $status_id;
const USER_STATUS_ACTIVE = 1;
const USER_STATUS_INACTIVE = 2;
const USER_STATUS_CANCELLED = 3;
static public function statusList() {
return array(User::USER_STATUS_ACTIVE => 'Active',User::USER_STATUS_INACTIVE => 'Inactive',User::USER_STATUS_CANCELLED => 'Cancelled');
}
public function setStatus($status_id) {
try {
if (!key_exists($status_id, User::statusList())) throw new Exception('Invalid status ID');
$this->status_id = $status_id;
}
catch (Exception $e) {
die($e);
}
}
}
$a = new User();
$a->setStatus(User::USER_STATUS_ACTIVE);
Alternately methods can be created for setActive(), setInactive(), setCancelled().
But what I'm trying to figure out is how to best handle the actual status values.
Would it be better to break the statuses out to a static class?
class User {
private $status_id;
public function setStatus($status_id) {
try {
if (!key_exists($status_id, UserStatuses::statusList())) throw new Exception('Invalid status ID');
$this->status_id = $status_id;
}
catch (Exception $e) {
die($e);
}
}
}
class UserStatuses {
const USER_STATUS_ACTIVE = 1;
const USER_STATUS_INACTIVE = 2;
const USER_STATUS_CANCELLED = 3;
static public function statusList() {
return array(UserStatuses::USER_STATUS_ACTIVE => 'Active',UserStatuses::USER_STATUS_INACTIVE => 'Inactive',UserStatuses::USER_STATUS_CANCELLED => 'Cancelled');
}
}
Or is there something entirely different that would be better?