在环境变量laravel中使用策略模式

qojgxg4l  于 2023-05-19  发布在  其他
关注(0)|答案(2)|浏览(188)

我目前正在学习设计模式,我遇到了策略模式。我理解它,但现在我想知道在运行时更改策略的最佳解决方案是什么。使用ENV变量是一个好的解决方案吗?示例:

interface Logger{
    public function log();
}

class SomeOtherLogger implements Logger {

public function log(){
    echo "Logging to something else";
 }
}

class FileLogger implements Logger {

public function log(){
    echo "Logging to file";
 }
}

class Main{
public function doSomething(Loggers $logger){
    $logger->log();    
 }
}

$main = new main();
$main->doSomething(new FileLogger);

我想到的一件事是使用环境变量,但我不确定什么是最好的方法,这对我来说似乎不正确。

$loggingStrategy = env('LOGGING_TYPE') . 'Logger';
$main = new main();
$main->doSomething(new $loggingStrategy);
lg40wkob

lg40wkob1#

如果你使用Laravel,我有一个更好的解决方案。我希望它对你有用:
Laravel有一个Manager基类,你可以用它来实现策略模式。考虑到我们想要伟大的用户取决于他们的语言。
首先,让我们实现我们的语言类:

namespace App\Welcome;

class English
{
    public function great()
    {
        return 'Hi!';
    }
}

对于德语:

namespace App\Welcome;

class German
{
    public function great()
    {
        return 'Halo!';
    }
}

现在我们创建一个Welcome类来扩展Laravel Manager基类:

namespace App;

use App\Welcome\English;
use App\Welcome\German;
use Illuminate\Support\Manager;

class Welcome extends Manager
{
    public function getDefaultDriver()
    {
        return 'english';
    }

    public function createGermanDriver()
    {
        return new German();
    }

    public function createEnglishDriver()
    {
        return new English();
    }
}

现在你可以使用strategy pattern为你的Welcome类定义一个default driver。如果你想在运行时改变驱动程序,你可以在welcome类上使用driver方法:

$greater = app(Welcome::class);
return $greater->driver('german')->great();

虽然这样,你也可以使用Laravel IOC container。但是如果你想更方便,可以将此模式与Laravel Facade功能结合起来。例如,在我们的示例中,您应该只将Facades前缀添加到欢迎类use关键字。最后的代码应该是这样的:

use Facades\App\Welcome; // <-- Laravel automatically would implement facade on the welcome class
  
Route::get('/', function () {
    return Welcome::driver('german')->great();
});
4si2a6ki

4si2a6ki2#

StrategyController.php

<?php
namespace App\Http\Controllers\DesignPattern\Strategy;

use App\Traits\ApiResponser;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Strategy\Sorting\SortingStrategyContext;

class StrategyController extends Controller
{
    use ApiResponser;
    public function sortingTest(Request $request)
    {
        $items = [5, 3, 2, 4, 1];

        $sortingstrategycontext = new SortingStrategyContext('quicksort');
        $sortedItems = $sortingstrategycontext->sort($items);

        return $this->set_response($sortedItems, 200,'success', ['Sorting!']);
    }
}

排序策略. php

<?php

namespace App\Strategy\Sorting;

interface SortingStrategy
{
    public function sort(array $items): array;
}

SortingStrategyContext.php

<?php

namespace App\Strategy\Sorting;

use App\Strategy\Sorting\SortingStrategy;
use App\Strategy\Sorting\BubbleSortStrategy;
use App\Strategy\Sorting\QuickSortStrategy;

class SortingStrategyContext
{
    private SortingStrategy $strategy;

    public function __construct( string $sortingStrategy )
    {
        switch ($sortingStrategy) {
            case 'bubblesort':
                $this->strategy = new BubbleSortStrategy();
                break;
            case 'quicksort':
                $this->strategy = new QuickSortStrategy();
                break;
            default:
                $this->strategy = new QuickSortStrategy();
                break;
        }
    }

    public function sort($items)
    {
        return $this->strategy->sort($items);
    }
}

BubbleSortStrategy.php

<?php

namespace App\Strategy\Sorting;

use App\Strategy\Sorting\SortingStrategy;

class BubbleSortStrategy implements SortingStrategy
{
    public function sort(array $items): array
    {
        $count = count($items);
        for ($i = 0; $i < $count; $i++) {
            for ($j = 0; $j < $count - $i - 1; $j++) {
                if ($items[$j] > $items[$j + 1]) {
                    $temp = $items[$j];
                    $items[$j] = $items[$j + 1];
                    $items[$j + 1] = $temp;
                }
            }
        }
        return $items;
    }
}

快速排序策略. php

<?php

namespace App\Strategy\Sorting;

use App\Strategy\Sorting\SortingStrategy;

class QuickSortStrategy implements SortingStrategy
{
    public function sort(array $items): array
    {
        if (count($items) <= 1) {
            return $items;
        }

        $pivot = array_shift($items);
        $left = $right = array();
        foreach ($items as $item) {
            if ($item < $pivot) {
                $left[] = $item;
            } else {
                $right[] = $item;
            }
        }

        return array_merge($this->sort($left), array($pivot), $this->sort($right));
    }
}

相关问题