Dima Dz
Dima Dz

Reputation: 538

ZF2 passing arguments to factories at runtime

In ZF2, I have a factory for a multicheckbox (simplified)

class MultiCheckboxFactory
{
    public function __invoke(FormElementManager $formElementManager)
    {
        $multiCheck = new MultiCheckbox();

        $serviceManager = $formElementManager->getServiceLocator();
        $mapper = $serviceManager->get('Path\To\The\Mapper\SomeMapper');
        $resultFromQuery = $mapper->findText('text');

        // further setting up of the multicheckbox based on $resultFromQuery

        return $multiCheck;
    }
}

I want the multicheckbox to render different content depending on $resultFromQuery that comes from the mapper's findText() method.

I thought of passing a variable to the __invoke(FormElementManager $formElementManager, $someText). But the problem is that when I call the multicheckbox from the service manager like this:

$element = $formElementManager->get('Path\To\Factory\Alias\Multicheckbox');

I don't see how to pass an additional variable. Any help?

Upvotes: 1

Views: 639

Answers (2)

David
David

Reputation: 875

Update: MutableCreationOptionsTrait is no longer available in ZF3: https://docs.zendframework.com/zend-servicemanager/migration/#miscellaneous-interfaces-traits-and-classes

The simplest way to do this now appears to be

$element = $formElementManager->build('Path\To\Factory\Alias\Multicheckbox', ['foo' => 'bar']);

though this will give you a discrete (not shared) instance every time.

Upvotes: 2

Bram Gerritsen
Bram Gerritsen

Reputation: 7238

Have a look at MutableCreationOptionsInterface, this allows your factory to receive runtime options which you pass through the serviceManager get() method.

use Zend\ServiceManager\MutableCreationOptionsInterface;
use Zend\ServiceManager\MutableCreationOptionsTrait;

class MultiCheckboxFactory implements MutableCreationOptionsInterface
{
    use MutableCreationOptionsTrait;

    public function __invoke(FormElementManager $formElementManager)
    {
        $options = $this->getCreationOptions();

        var_dump($options);

        $multiCheck = new MultiCheckbox();

        ....
    }
}

Now you can pass options:

$element = $formElementManager->get('Path\To\Factory\Alias\Multicheckbox', ['foo' => 'bar']);

Upvotes: 2

Related Questions