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
You can shorten your code by using one of the methods provided for backed enums and the nullsafe and null coalesce operators.
You can use
from(...)
instead oftryFrom(...)
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:
Then you can use it as:
Example
You can also move that method to a helper class somewhere else.
You can do something like that
or you can define a
method
in yourenum class
. In that method, you will pass adelivery 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
call it anywhere by this way