Skip to content

Instantly share code, notes, and snippets.

@BinaryKitten
Created August 18, 2021 13:39
Show Gist options
  • Save BinaryKitten/9b25de3c10a94f38b441cb1de4ca09be to your computer and use it in GitHub Desktop.
Save BinaryKitten/9b25de3c10a94f38b441cb1de4ca09be to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace App\Plans;
use \Exception;
class InvalidPlanClassException extends Exception
{
public static function for(string $classname): self
{
return new self('class with the name ' . $classname . ' did not extend/implement Plan');
}
}
<?php
declare(strict_types=1);
namespace App\Plans;
use \Exception;
class MissingPlanClassException extends Exception
{
public static function for(string $classname): self
{
return new self('A class with the name ' . $classname . ' could not be found');
}
}
<?php
declare(strict_types=1);
namespace App\Plans;
class PlanFactory
{
public function createPlan(string $plan = 'free'): Plan
{
$planName = 'App\\Plans\\' . ucwords($plan) . '\\Plan';
if (!class_exists($planName)) {
throw MissingPlanClassException::for($planName);
}
if (!$planName instanceof Plan) {
throw InvalidPlanClassException::for($planName);
}
return new $planName();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment