Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ray.Di car example
<?php
use Ray\Di\ProviderInterface;
use Ray\Di\Di\Inject;
interface CarInterface{}
interface CarConfigInterface{}
class CarConfig extends \ArrayObject implements CarConfigInterface{}
interface CarHelpersInterface{}
class CarHelpers extends \ArrayObject implements CarHelpersInterface{}
class SuperChargerHelper{}
class Car implements CarInterface
{
/**
* @Inject
*/
public function setHelpers(CarHelpersInterface $helpers)
{
$superChargerHelper = $helpers['super_charger'];
// or
foreach ($helpers as $helper) {
echo get_class($helper);
}
}
}
class HelperProvider implements ProviderInterface
{
private $config;
/**
* @Inject
*/
public function setHelperConfig(CarConfigInterface $config)
{
$this->config = $config;
}
public function get()
{
$helpers = new CarHelpers;
if (isset($this->config['super_charger'])) {
$chargerType = $this->config['super_charger']['type'];
$helpers['super_charger'] = new SuperChargerHelper($chargerType);
}
// ...
return $helpers;
}
}
class CarModule extends \Ray\Di\AbstractModule
{
public function __construct($carConfig)
{
$this->carConfig = $carConfig;
}
public function configure()
{
$this->bind('CarConfigInterface')->toInstance($this->carConfig);
$this->bind('CarHelpersInterface')->toProvider('HelperProvider');
}
}
//$carConfig = ...
$car = \Ray\Di\Injector::create([new CarModule($carConfig)])->getInstance('CarInterface');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment