Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Helpers Interface

Simple example, I have the following helpers interface for calculations:

interface Calculation
{
    public function calculate();
}

And a few classes that implement this interface:

class One implements Calculation
{
    public function calculate()
    {
        return some calculation;
    }
}


class Two implements Calculation
{
    public function calculate()
    {
        return some different calculation;
    }
}

// and so on..

Now, in my view I have the code that I displayed below, but I want to be able to get rid of the if's here. I would like to be able to do something like:

foreach($units as $unit)
{
        $total = (new \App\Helpers\{$unit})->calculate();
}

How would I go about this?

foreach($units as $unit)
{
    if($unit === 'One')
    {
        $total = (new \App\Helpers\One)->calculate();
    }

    if($unit === 'Two')
    {
        $total = (new \App\Helpers\Two)->calculate();
    }

    if($unit === 'Three')
    {
        $total = (new \App\Helpers\Three)->calculate();
    }

    if($unit === 'Four')
    {
        $total = (new \App\Helpers\Four)->calculate();
    }

    // and so on..
}
like image 882
Hardist Avatar asked Jun 26 '26 22:06

Hardist


1 Answers

Try this code:

   foreach($units as $unit)
    {
     $class="\\App\\Helpers\\".$unit;
     $total=(new $class)->calculate();
    }
like image 70
Yehia Awad Avatar answered Jun 29 '26 10:06

Yehia Awad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!