Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Best way to deal with duplicate statuses using enums and models

This question is related to formatting, presentation and autocompletion in regard to statuses. I haven’t found a way to use enums efficiently for more complex scenarios.

I have multiple tables

  • User
  • Post
  • Category

Every table has a status column as well as other enum columns. I have created the following enums:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • App\Enums\User\Status.php;
  • App\Enums\Post\Status.php;
  • App\Enums\Category\Status.php;

Inside of my code I need to refer to the statuses of every Model, such as:

$user->status = Status::APPROVED;
$post->status = Status::COMPLETE;
$category->status = Status::OPEN;

The statuses dont relate to each other and are all different for every model. The issue is related to formatting, since its very easy to confuse the statuses if they all have the same prefix.

I know I can also do this:

$user->status = \App\Enums\User\Status::APPROVED;
$post->status = \App\Enums\Post\Status::COMPLETE;
$category->status = \App\Enums\Category\Status::OPEN;

However that is not very clean and I wonder if there is any better way. Ideally I would like to do:

$user->status = User::Status::APPROVED;
$post->status = Post::Status::COMPLETE;
$category->status = Category::Status:OPEN;

I tried doing this in my model, but does not work since I cant instantiate a new object outside of a method:

class User extends Model
{
    public Status $STATUS = new Status();

The above gives me autocomplete and a clean syntax but it does not work obviously.

Are there any solutions for my use case? Something that gives me auto-completion and keeps code clean and short?

>Solution :

I think you can use

class User extends Model
{
    /** @var Status */
    public static $status = Status::class;
}

Or

use \App\Enums\User\Status as UserStatus
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading