Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How do I implement custom functions with the Enum base class
    BenSampo Laravel Enum Custom Methods BaseEnum PHP Enums Laravel-Enum


How do I implement custom functions with the Enum base class


The BenSampo/laravel-enum package provides a straightforward way to add custom methods to your Enum classes. Here's how you can do it:

1. Create a Base Enum Class:
Start by creating a base Enum class that will contain your custom methods. This allows you to reuse the methods across multiple Enum classes.

php
namespace App\Enums;

use BenSampo\Enum\Enum;

abstract class BaseEnum extends Enum
{
    /**
     * Get the display name of the enum value.
     *
     * @return string
     */
    public function getDisplayName(): string
    {
        return $this->description;
    }

    /**
     * Check if the enum value is final.
     *
     * @return bool
     */
    public function isFinal(): bool
    {
        return $this->isFinal;
    }
}

2. Extend Your Enum Classes from the Base Class:
Now, when you define your Enum classes, make them extend the `BaseEnum` class instead of the default `Enum` class.

php
namespace App\Enums;

final class Status extends BaseEnum
{
    const Initial = 1;
    const Pending = 2;
    const Completed = 3;
    const Canceled = 4;

    #[Description('Initial status')]
    #[IsFinal(false)]
    public const Initial = 1;

    #[Description('Pending status')]
    #[IsFinal(false)]
    public const Pending = 2;

    #[Description('Completed status')]
    #[IsFinal(true)]
    public const Completed = 3;

    #[Description('Canceled status')]
    #[IsFinal(true)]
    public const Canceled = 4;
}

3. Use the Custom Methods:
Now you can use the custom methods you defined in the `BaseEnum` class on your Enum instances.

php
$status = Status::Initial;
echo $status->getDisplayName(); // Output: "Initial status"
echo $status->isFinal(); // Output: false

This approach allows you to add custom functionality to your Enum classes without modifying the base `Enum` class provided by the BenSampo/laravel-enum package. You can add more custom methods to the `BaseEnum` class as needed, and all your Enum classes will inherit those methods.

Additionally, you can use the `#[Description]` and `#[IsFinal]` attributes to define the description and finality of your enum values, which can be accessed through the custom methods.

Citations:
[1] https://stackoverflow.com/questions/25705878/where-to-put-how-to-handle-enums-in-laravel
[2] https://laravelonline.com/articles/exploring-laravel-custom-casts-with-php-enums
[3] https://laravel-news.com/laravel-enum-package
[4] https://stackoverflow.com/questions/76281835/how-to-use-laravel-enum-by-extra-attributes-and-localization
[5] https://www.youtube.com/watch?v=0Ss-cRwd32o