Where to put/how to handle enums in Laravel?

后端 未结 6 1414
误落风尘
误落风尘 2020-12-24 10:22

Laravel has a

提交评论

  • 2020-12-24 10:49

    Building on @Banfords answer, with PHP7 constants can now be arrays:

    class User extends Authenticatable
    {
        /**
         * The possible genders a user can be.
         */
        const GENDER = [
            'Male',
            'Female',
            'Unspecified'
        ];
    
    ...
    
    0 讨论(0)
  • 2020-12-24 10:49

    Just had similar issue, for me Eloquent Accessors and mutators worked the best. For this question it would go like:

    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Customer extends Model
    {
        /**
        * @var array
        */
        protected $phoneTypes = [
            'Cellular',
            'Home',
            'Work'
        ];
    
       /**
        * @param int $value
        * @return string|null
        */
        public function getPhoneTypeAttribute($value)
        {
            return Arr::get($this->phoneTypes, $value);
        }
    }
    

    Please note that in database you should save numeric values, where 0 is cell, 1 is home and 2 is work. Secondly it would be wise to use translations here instead protected property.

    0 讨论(0)
  • 2020-12-24 10:54

    You have several options for handling enums. Before we look at a few though, I would first strongly encourage you not to use the DB enum column type.

    Database enums are problematic for a number of reasons. I suggest reading this article for example:

    http://komlenic.com/244/8-reasons-why-mysqls-enum-data-type-is-evil/

    So with that let's look at a few other options.

    Using Laravel config

    Since you're using Laravel, one very simple option is to stick an array of options in a config file.

    Say you create a new file config/enums.php with the following:

    return [
        'phone_types' => [
            'CELL' => "Cellular",
            'HOME' => "Home",
            'WORK' => "Work",
        ]
    ];
    

    You can now access config('enums.phone_types') anywhere in your code, including your Blade template.

    Using a PHP package

    @Banford's answer shows how to do basic enum-type behavior with class constants. If you like that approach, I recommend looking at this article and package which builds on this concept to provide strongly type enums:

    https://stitcher.io/blog/php-enums

    https://github.com/spatie/enum

    You would create a class like this:

    /**
     * @method static self cell()
     * @method static self home()
     * @method static self work()
     */
    class PhoneTypes extends Enum
    {
    }
    

    And now you can call PhoneTypes::home() in your app. Check out the documentation for that package to see how you can create a map of values, if you want.

    Using DB relationships

    If you really want to manage your options in the database, I'd create a separate phone_types database table and create a relationship with your customers table. This is still a much better option than using enum column type.

    0 讨论(0)
  • 2020-12-24 11:00

    I disagree with the accepted answer here. I feel that enums can be very useful for this kind of thing. I prefer to treat enums as types, and implement the methods you need on the Enum base class to give you the functionality you need such as getting a dictionary.

    My simple example below:

    abstract class PhoneType extends Enum {
        const Cell = "Cellular";
        const Home = "Home";
        const Work = "Work";
    }
    
    abstract class Enum {
        static function getKeys(){
            $class = new ReflectionClass(get_called_class());
            return array_keys($class->getConstants());
        }
    }
    

    Example usage:

    PhoneType::getKeys();
    

    See PHP and Enumerations for further details and a more in depth example.

    0 讨论(0)
  • 2020-12-24 11:10

    In addition to @Banford's answer:

    I have recently put together a package which makes working with enums in Laravel much nicer. It's a combination of various implementations I had found while researching how to do the very same thing (hence why I'm here).

    https://github.com/BenSampo/laravel-enum

    In this case, you could do something like the following:

    final class PhoneTypes extends Enum
    {
        const Cellular = 0;
        const Work = 1;
        const Home = 2;
    }
    

    The values can then be accessed using:

    PhoneTypes::Work // 1
    

    I would recommend always setting the values to integers and subsequently storing them in the DB as ints.

    The base Enum class has methods for getting all keys and values as arrays. The package also features a couple of other benefits which may be useful in this case such as validation - so that a user couldn't add a non-existent value to the DB.

    There's also a generator which is pretty handy.

    I hope this comes in useful for someone.

    0 讨论(0)
  • 提交回复
    热议问题