Kcko
3/16/2020 - 8:07 PM

6. Strategy

<?php

namespace RefactoringGuru\Strategy\Conceptual;

/**
 * The Context defines the interface of interest to clients.
 */
class Context
{
    /**
     * @var Strategy The Context maintains a reference to one of the Strategy
     * objects. The Context does not know the concrete class of a strategy. It
     * should work with all strategies via the Strategy interface.
     */
    private $strategy;

    /**
     * Usually, the Context accepts a strategy through the constructor, but also
     * provides a setter to change it at runtime.
     */
    public function __construct(Strategy $strategy)
    {
        $this->strategy = $strategy;
    }

    /**
     * Usually, the Context allows replacing a Strategy object at runtime.
     */
    public function setStrategy(Strategy $strategy)
    {
        $this->strategy = $strategy;
    }

    /**
     * The Context delegates some work to the Strategy object instead of
     * implementing multiple versions of the algorithm on its own.
     */
    public function doSomeBusinessLogic(): void
    {
        // ...

        echo "Context: Sorting data using the strategy (not sure how it'll do it)\n";
        $result = $this->strategy->doAlgorithm(["a", "b", "c", "d", "e"]);
        echo implode(",", $result) . "\n";

        // ...
    }
}

/**
 * The Strategy interface declares operations common to all supported versions
 * of some algorithm.
 *
 * The Context uses this interface to call the algorithm defined by Concrete
 * Strategies.
 */
interface Strategy
{
    public function doAlgorithm(array $data): array;
}

/**
 * Concrete Strategies implement the algorithm while following the base Strategy
 * interface. The interface makes them interchangeable in the Context.
 */
class ConcreteStrategyA implements Strategy
{
    public function doAlgorithm(array $data): array
    {
        sort($data);

        return $data;
    }
}

class ConcreteStrategyB implements Strategy
{
    public function doAlgorithm(array $data): array
    {
        rsort($data);

        return $data;
    }
}

// USAGE
/**
 * The client code picks a concrete strategy and passes it to the context. The
 * client should be aware of the differences between strategies in order to make
 * the right choice.
 */
$context = new Context(new ConcreteStrategyA);
echo "Client: Strategy is set to normal sorting.\n";
$context->doSomeBusinessLogic();

echo "\n";

echo "Client: Strategy is set to reverse sorting.\n";
$context->setStrategy(new ConcreteStrategyB);
$context->doSomeBusinessLogic();
<?php

interface Comparator
{
    /**
     * @param mixed $a
     * @param mixed $b
     *
     * @return int
     */
    public function compare($a, $b): int;
}


class DateComparator implements Comparator
{
    public function compare($a, $b): int
    {
        $aDate = new DateTime($a['date']);
        $bDate = new DateTime($b['date']);

        return $aDate <=> $bDate;
    }
}


class IdComparator implements Comparator
{
    public function compare($a, $b): int
    {
        return $a['id'] <=> $b['id'];
    }
}


class Context
{
    private Comparator $comparator;

    public function __construct(Comparator $comparator)
    {
        $this->comparator = $comparator;
    }

    public function executeStrategy(array $elements): array
    {
        uasort($elements, [$this->comparator, 'compare']);

        return $elements;
    }
}

// Usage
// $dataCollection of some datas ...
$obj = new Context(new IdComparator());
// or
$obj = new Context(new DateComparator());
//result
$elementsCompared = $obj->executeStrategy($dataCollection);
<?php

Interface Product_Type {
    public function get_all();
    
    //skipped other function definitions to keep this example simple
}
 
Class Shoe implements Product_Type {
    public function get_all() { return DB::table('shoes')->all(); }
}
 
Class Apparel implements Product_Type {
    public function get_all() { return DB::table('apparels')->all(); }
}
 
Class Mobiles implements Product_Type {
    public function get_all() { return DB::table('mobiles')->all(); }
}


// STD USAGE - BAD USAGE
if( $product_type == 'shoes' ) {
    $product_obj = new Shoe();
}
elseif( $product_type == 'apparels' ) {
    $product_obj = new Shoe();
}
elseif( $product_type == 'mobiles' ) {
    $product_obj = new Mobile();
}
 
$all_products = $product_obj->get_all();


// GOOD USAGE
Class Listing {
    private $product_type;
    
    public function set_product_type($product_type) {
        if( $product_type == 'shoes' ) {
            $this->product_type = new Shoe();
        }
        elseif( $product_type == 'apparels' ) {
            $this->product_type = new Apparels();
        }
        elseif( $product_type == 'mobiles' ) {
            $this->product_type = new Mobile();
        }               
    }
    
    public function get_all() {
        return $this->product_type->get_all();
    }
}
 
$listing_obj = new Listing();
$listing_obj->set_product_type($product_type);
$all_products = $listing_obj->get_all();
<?php

$exampleData = [
    "name" => "Johhny",
    "surname" => "Marrony",
    "company" => "Company",
    "position" => "Senior Doorkeeper"
];

$jsonContext = new Context('json');
echo $jsonContext->formatData($exampleData) . PHP_EOL;

$stringContext = new Context('string');
echo $stringContext->formatData($exampleData) . PHP_EOL;

$xmlContext = new Context('xml');
echo $xmlContext->formatData($exampleData) . PHP_EOL;


// 
interface OutputFormatter {

    public function format (array $data): string;

}


class Context {

    private $formatter;

    public function __construct (string $outputType) {
        switch ($outputType) {
            case "json":
                $this->formatter = new JSONFormatter();
                break;
            case "xml":
                $this->formatter = new XMLFormatter();
                break;
            case "string":
                $this->formatter = new StringFormatter();
                break;
            default:
                throw new \InvalidArgumentException("{$outputType} is not supported");
        }
    }

    public function formatData (array $data): string {
        return $this->formatter->format($data);
    }
}



use SimpleXMLElement;
class XMLFormatter implements OutputFormatter {

    public function format (array $data): string {
        $xml = $this->addData($data, new SimpleXMLElement('<root/>'));

        return $xml->asXML();
    }

    protected function addData (array $data, SimpleXMLElement $xml) {
        foreach ($data as $k => $v) {
            is_array($v)
                ? $this->addData($v, $xml->addChild($k))
                : $xml->addChild($k, $v);
        }
        return $xml;
    }
}


class StringFormatter implements OutputFormatter {

    const DELIMITER = ",";

    public function format (array $data): string {
        return implode(self::DELIMITER, $data);
    }
}


class JSONFormatter implements OutputFormatter {

    public function format (array $data): string {
        return json_encode($data);
    }
}
<?php

class LazyFileReaderManager
{

	/** @var array<string, string> */
	private array $readers = [
		'neon' => NeonFileReader::class,
		'xml' => XmlFileReader::class,
		'yaml' => YamlFileReader::class,
	];

	/** @var array<string, FileReader> */
	private array $instances = [];

	public function get(string $suffix): FileReader
	{
		if (isset($this->instances[$suffix])) {
			return $this->instances[$suffix];
		}

		if (!isset($this->readers[$suffix])) {
			throw new InvalidArgumentException(sprintf(
				'File reader for suffix `%s` does not exist.',
				$suffix
			));
		}

		return $this->instances[$suffix] = new $suffix();
	}

	public function add(string $suffix, FileReader $reader): void
	{
		$this->instances[$suffix] = $reader;
	}

}