Skip to content

Instantly share code, notes, and snippets.

@pavelkucera
Last active December 20, 2015 22:59
Show Gist options
  • Save pavelkucera/6208889 to your computer and use it in GitHub Desktop.
Save pavelkucera/6208889 to your computer and use it in GitHub Desktop.
How to add a factory taking parameter into Nette DIC. Both ways, using config.neon and compiler extension, have the same result.
factories:
formMapperFactory:
create: Namespace\FormMapper(..., %form%)
implement: Namespace\IFactory
parameters: [Namespace\Form form]
<?php
class Extension extends \Nette\DI\CompilerExtension
{
public function loadConfiguration()
{
$container = $this->getContainerBuilder();
$container->addDefinition($this->prefix('formMapperFactory'))
->setImplement('Namespace\IFactory')
->setParameters(['Namespace\Form form'])
->setFactory('Namespace\FormMapper', [
'form' => new \Nette\PhpGenerator\PhpLiteral('$form'),
])
->setAutowired(TRUE);
}
}
<?php
namespace Namespace;
interface IFactory
{
/**
* @param \Namespace\Form $form
* @return \Namespace\FormMapper
*/
function create(\Namespace\Form $form);
}
<?php
$factory->create(new Namespace\Form());
@klobinoid
Copy link

Thx, helped me today!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment