Created
April 9, 2024 15:47
-
-
Save atakde/6e066698afd06a056a7329d1866ea374 to your computer and use it in GitHub Desktop.
State pattern in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Interface for states | |
interface DeploymentState | |
{ | |
public function handle(DeploymentManager $manager); | |
} | |
// Concrete state class | |
class PendingState implements DeploymentState | |
{ | |
public function handle(DeploymentManager $manager) | |
{ | |
echo "Deployment is pending.\n"; | |
// Transition to next state | |
$manager->setState(new DeployingState()); | |
} | |
} | |
// Concrete state class | |
class DeployingState implements DeploymentState | |
{ | |
public function handle(DeploymentManager $manager) | |
{ | |
echo "Deploying...\n"; | |
sleep(5); | |
$manager->setState(new DeployedState()); | |
} | |
} | |
// Concrete state class | |
class DeployedState implements DeploymentState | |
{ | |
public function handle(DeploymentManager $manager) | |
{ | |
echo "Deployment is successful.\n"; | |
} | |
} | |
// The context class | |
class DeploymentManager | |
{ | |
private $state; | |
public function __construct() | |
{ | |
$this->setState(new PendingState()); | |
} | |
public function setState(DeploymentState $state) | |
{ | |
$this->state = $state; | |
} | |
public function deploy() | |
{ | |
$this->state->handle($this); | |
} | |
} | |
// Example | |
$manager = new DeploymentManager(); | |
$manager->deploy(); // Output: Deployment is pending. | |
$manager->deploy(); // Output: Deploying... | |
$manager->deploy(); // Output: Deployment is successful. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment