PHP code example of konekt / enum-eloquent

1. Go to this page and download the library: Download konekt/enum-eloquent library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

konekt / enum-eloquent example snippets


namespace App;

use Konekt\Enum\Enum;

class OrderStatus extends Enum
{
    const __DEFAULT = self::PENDING; 
    // const __default = self::PENDING; // usage of default in v2.x 

    const PENDING   = 'pending';
    const CANCELLED = 'cancelled';
    const COMPLETED = 'completed';

}

namespace App;

use Illuminate\Database\Eloquent\Model;
use Konekt\Enum\Eloquent\CastsEnums;

class Order extends Model
{
    use CastsEnums;

    protected $enums = [
        'status' => OrderStatus::class
    ];
}

$order = Order::create([
    'status' => 'pending'
]);

// The status attribute will be an enum object:
echo get_class($order->status);
// output: App\OrderStatus

echo $order->status->value();
// output: 'pending'

echo $order->status->isPending() ? 'yes' : 'no';
// output: yes

echo $order->status->isCancelled() ? 'yes' : 'no';
// output: no

// You can assign an enum object as attribute value:
$order->status = OrderStatus::COMPLETED();
echo $order->status->value();
// output: 'completed'

// It also works with mass assignment:
$order = Order::create([
    'status' => OrderStatus::COMPLETED()    
]);

echo $order->status->value();
// output 'completed'

// It still accepts scalar values:
$order->status = 'completed';
echo $order->status->isCompleted() ? 'yes' : 'no';
// output: yes

// But it doesn't accept scalar values that aren't in the enum:
$order->status = 'negotiating';
// throws UnexpectedValueException
// Given value (negotiating) is not in enum `App\OrderStatus`

namespace App;

use Illuminate\Database\Eloquent\Model;
use Konekt\Enum\Eloquent\CastsEnums;

class Order extends Model
{
    use CastsEnums;

    protected $enums = [
        'status' => 'OrderStatusResolver@enumClass'
    ];
}

namespace App;

class OrderStatusResolver
{
    /**
     * Returns the enum class to use as order status enum
     *
     * @return string
     */
    public static function enumClass()
    {
        return config('app.order.status.class', OrderStatus::class);
    }
}