Skip to content

Instantly share code, notes, and snippets.

@mikemix
Last active September 18, 2015 08:08
Show Gist options
  • Save mikemix/e5221cf532cf7366a344 to your computer and use it in GitHub Desktop.
Save mikemix/e5221cf532cf7366a344 to your computer and use it in GitHub Desktop.
<?php
interface JobInterface
{
/**
* Czy wartość spełnia kryteria?
*
* @param mixed $value
* @return bool
*/
public function isSatisified($value);
/**
* @return mixed
*/
public function doJob();
}
class Job1 implements JobInterface
{
public function isSatisified($value)
{
return $value === 0;
}
public function doJob()
{
printf("%s doing the job<br>", __METHOD__);
}
}
class Job2 implements JobInterface
{
public function isSatisified($value)
{
return $value === 1;
}
public function doJob()
{
printf("%s doing the job<br>", __METHOD__);
}
}
class JobExecuter
{
private $jobs = [];
/**
* iniekcja przez konstruktor
* @param JobInterface[] $jobs
*/
public function __construct(array $jobs)
{
$this->jobs = $jobs;
}
/**
* lub jak kto woli przez metodę
* @param JobInterface $job
*/
public function addJob(JobInterface $job)
{
$this->jobs[] = $job;
}
public function execute($value)
{
foreach ($this->jobs as $job) {
if ($job->isSatisfied($value)) {
return $job->doJob($value);
}
}
throw new \RuntimeException(sprintf('No job executed for %d', $value));
}
}
$runner = new JobExecuter();
$runner->addJob(new Job1());
$runner->addJob(new Job2());
// lub
$runner = new JobExecuter([new Job1(), new Job2()])
$runner->execute(mt_rand(0,1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment