spatie / enum

Strongly typed enums in PHP supporting autocompletion and refactoring
https://docs.spatie.be/enum/v3/introduction
MIT License
771 stars 67 forks source link

initialize Enum with values coming from DB? #110

Closed wivaku closed 2 years ago

wivaku commented 3 years ago

Could be I am asking a silly question.

I have valid codes stored in a database. Would like to create an Enum using the values in the database.

So instead of:

/**
 * @method static self draft()
 * @method static self published()
 * @method static self archived()
 */
class StatusEnum extends Enum
{
}

Something like:

class StatusEnum extends Enum
{
    protected static function values(): array
    {
        // example attempt, getting code values from DB
        return StatusType::all()->pluck('code')->toArray(); // ['draft','published','archived']
    }
}

Expected end result for both is that it is possible to call StatusEnum::draft().

But my attempt results in an Enum without any values (because it seems to rely on the docblocks for definition):

StatusEnum::toValues() // []

Is there a way for the package to support this flow?

It might sound counterintuitive to have dynamic codes in the DB and have a hardcoded Enum (i.e. hardcoded StatusEnum::draft()), but this way I can deploy + code using default values and I don't have to redeploy if I ever have to add values. And: otherwise the Enum would be also be hardcoded: in the docblock.

Gummibeer commented 3 years ago

Hey, it's possible by overriding the underlying logic how we resolve the doc-block. But I can only recommend you to don't do it. If you want to use a model/table use relations. Or use a hardcoded enum. With PHP8.1 you won't be able at all to use your DB as the values for an enum - so it would be something for only a few months.

github-actions[bot] commented 2 years ago

This issue is stale because it has been open 21 days with no activity. Remove stale label or comment or this will be closed in 7 days