Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created August 14, 2018 15:08
Show Gist options
  • Save kobus1998/dce8c24434051a1549100d0719a5f4c0 to your computer and use it in GitHub Desktop.
Save kobus1998/dce8c24434051a1549100d0719a5f4c0 to your computer and use it in GitHub Desktop.
SImple service runner including adapter
<?php
$serviceContainer = new ServiceContainer();
$serviceContainer->add("my service", MyService::class);
$serviceRunner = new ServiceRunner($serviceContainer, MyServiceAdapter::class);
$serviceRunner->exec();
<?php
class MyService implements ServiceInterface
{
public function boot() {
echo "booting..\n";
}
public function run() {
echo "running...\n";
}
}
<?php
class MyServiceAdapter implements ServiceRunnerAdapter {
public function exec(array $services) {
foreach ($services as $service) {
$service->run();
}
}
}
<?php
interface ServiceRunnerAdapter {
public function exec(array $services);
}
<?php
class ServiceContainer {
private $services;
public function add($name, $instance)
{
$this->services[$name] = $instance;
}
public function boot()
{
foreach($this->services as $name => $instance) {
if (is_string($instance)) {
$this->services[$name] = new $instance();
$this->services[$name]->boot();
}
}
}
public function get()
{
$this->boot();
return $this->services;
}
}
<?php
interface ServiceInterface {
public function run();
}
<?php
class ServiceRunner {
private $container;
private $adapter;
public function __construct(ServiceContainer $container, ServiceRunnerAdapter $adapter = null) {
$this->container = $container;
if ($adapter != null) {
if (is_string($adapter)) {
$this->adapter = new Adapter();
} else {
$this->adapter = $adapter;
}
}
$this->adapter = $adapter;
}
public function exec() {
$services = $this->container->get();
if ($this->adapter != null) {
$this->adapter->exec($services);
} else {
foreach($this->container->get() as $name => $instance) {
$instance->run();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment