Skip to content

Instantly share code, notes, and snippets.

@settermjd
Created July 24, 2015 10:37
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 settermjd/90b8e26cbd123ed6ec0b to your computer and use it in GitHub Desktop.
Save settermjd/90b8e26cbd123ed6ec0b to your computer and use it in GitHub Desktop.
Issue with using a factory to retrieve a service in PHP-DI
<?php
use DiExample\DummyDateCalculatorFactory;
return [
'DateTime' => new \DateTime(),
'calculator' => [DI\get('DiExample\DummyDateCalculatorFactory'), 'create'],
];
<?php
namespace DiExample;
class DummyDateCalculator
{
protected $date;
protected $secondDate;
public function __construct(\DateTime $date)
{
$this->date = $date;
}
public function setSecondDate(\DateTime $secondDate)
{
$this->secondDate = $secondDate;
}
public function __toString()
{
return "Time was initialised at: " . $this->date->format(\DateTime::ATOM);
}
}
<?php
namespace DiExample;
use Interop\Container\ContainerInterface;
class DummyDateCalculatorFactory
{
/**
* @param $container
* @return DummyDateCalculator
*/
public function create(ContainerInterface $container)
{
return new DummyDateCalculator($container->get('DateTime'));
}
}
<?php
date_default_timezone_set('UTC');
require_once('vendor/autoload.php');
$builder = new DI\ContainerBuilder();
$builder->addDefinitions('config/config.php');
$container = $builder->build();
var_dump($container->get('calculator'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment