skip to Main Content

I have been learning the new enums introduction on php 8.1 with laravel for an eccomerce cms. i’m brandly new on SOLID principles.

This this my Enum class:

enum PaymentMethods : string
{
    case PAYPAL  = 'pay with paypal';
    case STRIPE  = 'pay with stripe';
}

On checkout page user can select one of Payment Methods like this:

<select name="delivery_method">
    @foreach(DeliveryMethods::cases() as $case)
        <option value="{{ $case->name }}">{{ $case->value }}</option>
    @endforeach
</select>

let’s assume that we have PAYPAL value (which is taken from user input), in the view and we want to access the value of PAYPAL from PaymentMethods Enum class,

one method is that i use a foreach loop like this:

<p>
    @foreach(DeliveryMethods::cases() as $case)
        @if(request()->get('payment_method') == $case->name)
            {{ $case->value }}
        @endif
    @endforeach
</p>

but i want to use this logic in different places and on many times,
is there any better way instead of doing this, based on solid prinsiples?

2

Answers


  1. You can shorten your code by using one of the methods provided for backed enums and the nullsafe and null coalesce operators.

    {{ DeliveryMethods::tryFrom(request()->get('payment_method'))?->value ?? 'some default value' }}
    

    You can use from(...) instead of tryFrom(...) if you want your code to fail if an invalid enum value is passed instead of dealing with nulls.

    This is assuming you are using the values to access the cases. If you are using the name then it gets trickyer. You can implement static methods in enums:

    enum PaymentMethods : string
    {
        case PAYPAL  = 'pay with paypal';
        case STRIPE  = 'pay with stripe';
        
        public static function fromName(string $method): PaymentMethods
        {
            foreach(PaymentMethods::cases() as $case) {
               if ($case->name === $method) {
                  return $case;
                }
            }
            return null;
        }
    }
    

    Then you can use it as:

    PaymentMethods::fromName(request()->get('payment_method'));
    

    Example

    You can also move that method to a helper class somewhere else.

    Login or Signup to reply.
  2. You can do something like that

    PaymentMethods::{$selected_method}->value
    

    Note: here $selected_method is the value you obtain from view by user.

    or you can define a method in your enum class. In that method, you will pass a delivery method name as a string and that method will evaluate the value of a selected method. i.e.

    Define that method in the enum class
    public function getVal($method)
    {
       $this::{$method}->value;
    }
    
    
    call it anywhere by this way
    PaymentMethods::getVal("PAYPAL");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search