Skip to content

Instantly share code, notes, and snippets.

@hallboav
Last active May 23, 2019 02:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hallboav/2267c94aa01fb196b509025727f9cba6 to your computer and use it in GitHub Desktop.
Save hallboav/2267c94aa01fb196b509025727f9cba6 to your computer and use it in GitHub Desktop.
State machine
<?php
interface PortaInterface
{
public function abrir();
public function fechar();
}
abstract class AbstractPorta implements PortaInterface
{
public function abrir()
{
throw new \BadMethodCallException('Não é possível abrir esta porta.');
}
public function fechar()
{
throw new \BadMethodCallException('Não é possível fechar esta porta.');
}
}
class PortaFechada extends AbstractPorta
{
public function abrir()
{
return new PortaAberta();
}
}
class PortaAberta extends AbstractPorta
{
public function fechar()
{
return new PortaFechada();
}
}
$initialState = new PortaFechada();
$initialState
->abrir()
->fechar()
->abrir()
->fechar();
<?php
interface PortaInterface
{
public function abrir();
public function fechar();
}
class Porta implements PortaInterface
{
private $isAberta;
public function __construct($isAberta)
{
$this->isAberta = $isAberta;
}
public function abrir()
{
if ($this->isAberta) {
throw new \BadMethodCallException('Não é possível abrir esta porta.');
}
$this->isAberta = true;
return $this;
}
public function fechar()
{
if (!$this->isAberta) {
throw new \BadMethodCallException('Não é possível fechar esta porta.');
}
$this->isAberta = false;
return $this;
}
}
$porta = new Porta(false);
$porta
->abrir()
->fechar()
->abrir()
->fechar();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment