Skip to content

Instantly share code, notes, and snippets.

@diloabininyeri
Created October 2, 2022 21:14
Show Gist options
  • Select an option

  • Save diloabininyeri/90323a0f15cfc3169ab379e4186fda75 to your computer and use it in GitHub Desktop.

Select an option

Save diloabininyeri/90323a0f15cfc3169ab379e4186fda75 to your computer and use it in GitHub Desktop.
php filter desing pattern
<?php
$persons = [
[
'name' => 'ali',
'gender' => 'man',
'age' => 18
],
[
'name' => 'deniz',
'gender' => 'woman',
'age' => 25
],
[
'name' => 'ahmet',
'gender' => 'man',
'age' => 14
],
];
interface Filterable
{
public function filter(array $persons): array;
}
class ManFilter implements Filterable
{
/**
* @param array $persons
* @return array
*/
public function filter(array $persons): array
{
return array_values(
array_filter(
$persons,
static fn($person) => $person['gender'] === 'man'
)
);
}
}
class AgeFilter implements Filterable
{
public function __construct(private readonly int $age)
{
}
/**
* @param array $persons
* @return array
*/
public function filter(array $persons): array
{
return array_values(
array_filter($persons, fn($person) => $person['age'] > $this->age)
);
}
}
class FilterOperation implements Filterable
{
/**
* @var Filterable[] $filters
*/
private array $filters = [];
public function add(Filterable $filterable): self
{
$this->filters[] = $filterable;
return $this;
}
/**
* @param array $persons
* @return array
*/
public function filter(array $persons): array
{
foreach ($this->filters as $filter) {
$persons = $filter->filter($persons);
}
return $persons;
}
}
$filter = new FilterOperation();
$filter
->add(new AgeFilter(17))
->add(new ManFilter());
$filter->filter($persons); //['name'=>'ali,'gender'=>'man','age'=>18]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment