Skip to content

Instantly share code, notes, and snippets.

@bcremer
Last active January 25, 2017 02:33
Show Gist options
  • Save bcremer/4122ee0ebf81091da0fd to your computer and use it in GitHub Desktop.
Save bcremer/4122ee0ebf81091da0fd to your computer and use it in GitHub Desktop.
Liskov substitution principle Violation
<?php
// conditions are just semantic value objects containing constraint data
// handlers now how to interact with a condition it supports and operates on the given $querybuilder
// The LSP Violation happens in the generateCondition() method of the handler where we want to pull additional values from the condition object.
$condition = new SearchTermCondition("foobar");
$handler = new SearchTermConditionHandler();
if ($handler->supportsCondition($condition)) {
$handler->generateCondition($condition, $queryBuilder);
}
interface ConditionInterface
{
public function getName();
}
interface ConditionHandlerInterface
{
public function supportsCondition(ConditionInterface $condition);
public function generateCondition(
ConditionInterface $condition,
QueryBuilder $qb,
);
}
class SearchTermCondition implements ConditionInterface
{
public function __construct($term)
{
$this->term = $term;
}
public function getName()
public function getTerm(); // additional method not defined in ConditionInterface
}
class SearchTermConditionHandler implements ConditionHandlerInterface
{
public function supportsCondition(ConditionInterface $condition)
{
return ($condition instanceof SearchTermCondition);
}
public function generateCondition(ConditionInterface $condition, QueryBuilder $qb)
{
$term = $condition->getTerm(); // Violation of LSP, getTerm() is not defined in ConditionInterface
$qb->andWhere('term = ?', $term)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment