Laravel - Where to store statuses (flags)? Model, Class or config folder?
In my applications I do similar to @Martin Bean except I don't create separate classes for status, I store that inside the existent class/Model.
I'm going to call user
, subscription
and entity
a entity.
- Entity have a
status
that exists in it's Model and table in the database. - Each Model have constants of possible values of
status
likeACTIVE
,INACTIVE
,PENDING
, etc, and those may vary for each Model. - Create methods for dealing with it like
getStatusLabel()
,listStatus()
,isActive()
,isX()
, etc. - Those
isActive/X()
are only created if really necessary, maybe a Model have 4 status but you only do comparisons against one specific, so I'd create only oneisX()
for that status.
Example
class User
{
const STATUS_ACTIVE = 1;
const STATUS_SUSPENDED = 2;
const STATUS_INACTIVE = 3;
/**
* Return list of status codes and labels
* @return array
*/
public static function listStatus()
{
return [
self::STATUS_ACTIVE => 'Active',
self::STATUS_SUSPENDED => 'Suspended',
self::STATUS_INACTIVE => 'Inactive'
]
}
/**
* Returns label of actual status
* @param string
*/
public function statusLabel()
{
$list = self::listStatus();
// little validation here just in case someone mess things
// up and there's a ghost status saved in DB
return isset($list[$this->status])
? $list[$this->status]
: $this->status;
}
/**
* Some actions will happen only if it's active, so I have
* this method for making things easier.
* Other status doesn't have a specific method because
* I usually don't compare agains them
* @return Boolean
*/
public function isActive()
{
return $this->status == self::STATUS_ACTIVE;
}
}
I tend to create a specific model for statuses, that acts as an enum. So if I have an Event
model, I may have a corresponding EventStatus
model that looks like this:
class EventStatus
{
public const CANCELLED = 'EventCancelled';
public const POSTPONED = 'EventPostponed';
public const RESCHEDULED = 'EventRescheduled';
public const SCHEDULED = 'EventScheduled';
}
I can then do checks like this:
$event->status === EventStatus::CANCELLED;
And I’ll usually add convenience methods to my models too:
class Event extends Model
{
public function isCancelled(): bool
{
return $this->status === EventStatus::CANCELLED;
}
}
For the “human-friendly” strings, I’ll then have a language file that has the text strings:
<?php // resources/lang/en/event_status.php
return [
EventStatus::CANCELLED => 'Cancelled',
EventStatus::POSTPONED => 'Postponed',
EventStatus::RESCHEDULED => 'Rescheduled',
EventStatus::SCHEDULED => 'Scheduled',
];