Skip to content

Instantly share code, notes, and snippets.

@atakde
Created April 9, 2024 15:47
Show Gist options
  • Save atakde/6e066698afd06a056a7329d1866ea374 to your computer and use it in GitHub Desktop.
Save atakde/6e066698afd06a056a7329d1866ea374 to your computer and use it in GitHub Desktop.
State pattern in PHP
<?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