Skip to content

Instantly share code, notes, and snippets.

@koriym
Created September 13, 2014 03:24
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 koriym/490adf441037bae0167f to your computer and use it in GitHub Desktop.
Save koriym/490adf441037bae0167f to your computer and use it in GitHub Desktop.
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