Skip to content

Instantly share code, notes, and snippets.

@david4worx
Created January 24, 2012 14:17
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 david4worx/1670386 to your computer and use it in GitHub Desktop.
Save david4worx/1670386 to your computer and use it in GitHub Desktop.
Adapters
<?php
interface FilterAdapter
{
public function filter($value);
}
class FilterBase
{
protected $_adapter;
public function getAdapter()
{
return $this->_adapter;
}
public function setAdapter(FilterAdapter $filter)
{
$this->_adapter = $filter;
return $this;
}
public function filter($value)
{
return $this->getAdapter()->filter($value);
}
}
//Old filter adapter
class FilterArrayAdapterHard implements FilterAdapter
{
public function filter($value)
{
if (!is_array($value)) {
throw new InvalidArgumentException('$value should be an array.');
}
$tmp = array();
foreach ($value as $k => $v) {
if (!empty($v)) {
$tmp[$k] = $v;
}
}
return $tmp;
}
}
//New filter adapter
class FilterArrayAdapterEasy implements FilterAdapter
{
public function filter($value)
{
if (!is_array($value)) {
throw new InvalidArgumentException('$value should be an array.');
}
return array_filter($value);
}
}
$foo = array('foo', 'bar', 0);
$filter = new FilterBase();
var_dump($filter->setAdapter(new FilterArrayAdapterEasy())->filter($foo));
<?php
interface FilterAdapter
{
public function filter($value);
}
class FilterBase
{
protected $_adapter;
public function getAdapter()
{
return $this->_adapter;
}
public function setAdapter(FilterAdapter $filter)
{
$this->_adapter = $filter;
return $this;
}
public function filter($value)
{
return $this->getAdapter()->filter($value);
}
}
class FilterArrayAdapterHard implements FilterAdapter
{
public function filter($value)
{
if (!is_array($value)) {
throw new InvalidArgumentException('$value should be an array.');
}
$tmp = array();
foreach ($value as $k => $v) {
if (!empty($v)) {
$tmp[$k] = $v;
}
}
return $tmp;
}
}
$foo = array('foo', 'bar', 0);
$filter = new FilterBase();
var_dump($filter->setAdapter(new FilterArrayAdapterHard())->filter($foo));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment