📜  laravel-enum (1)

📅  最后修改于: 2023-12-03 15:17:17.284000             🧑  作者: Mango

Laravel-Enum

Laravel-Enum is a package that allows for the creation and usage of enumerations in Laravel applications. This package provides an easy way to define enums and use them in your application code.

Installation

Laravel-Enum can be installed via composer using the following command:

composer require benSassi/laravel-enum

You can also add the package as a dependency in your composer.json file:

"require": {
    "benSassi/laravel-enum": "^1.0"
}
Usage
Defining Enums

The Enum class is provided to define your enums. You can define an enum by extending the Enum class and using constants to define the values:

namespace App\Enums;

use benSassi\Enum\Enum;

final class Status extends Enum
{
    const PENDING = 'pending';
    const APPROVED = 'approved';
    const REJECTED = 'rejected';
}

You can also define enums using an array:

namespace App\Enums;

use benSassi\Enum\Enum;

final class Role extends Enum
{
    protected static $values = [
        'ADMIN' => 'Admin',
        'MANAGER' => 'Manager',
        'EMPLOYEE' => 'Employee',
    ];
}
Using Enums

You can use enums in your application code by calling their values as follows:

use App\Enums\Status;

if ($status === Status::PENDING) {
    // Do something
}

You can also get a list of values by calling the values() method:

use App\Enums\Status;

$statuses = Status::values();
Casting Enums

Laravel-Enum also provides an easy way to cast your enums to different data types. You can cast an enum to a string, integer, or boolean by using the EnumType class and specifying the type in your migration file:

use App\Enums\Role;
use benSassi\Enum\Database\Type\EnumType;

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('role')->default(Role::EMPLOYEE)->index();
        });
        DB::statement('ALTER TABLE users MODIFY role ENUM(\'Admin\', \'Manager\', \'Employee\')');
        Doctrine::getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
        $this->connection
            ->getDoctrineSchemaManager()
            ->getDatabasePlatform()
            ->registerDoctrineTypeMapping('enum', 'string');
    }
}
Custom Enum Classes

If you need to customize the behavior of your enums, you can create a custom enum class and have them extend the Enum class:

namespace App\Enums;

use benSassi\Enum\Enum;

class MyEnum extends Enum
{
    // Customize your enum here
}
Conclusion

Laravel-Enum provides an easy way to define and use enums in Laravel applications. With this package, you can improve the readability and maintainability of your code, making it easier to work with enums in your application.