Migration ZF2 ==> ZF3: get an object instance through IOC + (__invoke + $options parameter)

Hello,

I’ve a question about how to get with the creation inversion (IOC), via $goServiceManager->get(‘Foo’);, an object instance by passing something to inject with the $option parameter of the __invoke FactoryInterface’s method.

For example, I have the following factory:

class LogNamedFactory implements Zend\ServiceManager\FactoryInterface {

	public function createService(Zend\ServiceManager\ServiceLocatorInterface $serviceLocator) {
		// not used, for the moment
	}

	public function __invoke(ContainerInterface $container/*a.k.a $goSiteManager*/, $requestedName, array $options = null) {
		$oLogNamed = new \stdClass(); 
		$oLogNamed->sFullPathLogName = $options['sFullPathLogName'];
		return $oLogNamed;
	}
}

Then, I’m “learning” the ServiceManager how to create one with the IOC:

$goServiceManager->setFactory('LogNamed', LogNamed::class);

I’m stuck here: is it possible - in one line - to say that I want to get an LogNamed object instance by passing\using the factory’s $option parameter, setting it with the path of a log filename? Something like:

$oMyLogNamed = $goServiceManager->get('LogNamed')[basename($sFullPathLogFileName)];  // (???)
$oMyLogNamed = $goServiceManager->get('LogNamed')->???(basename($sFullPathLogFileName));  // (???)

Should I create a real LogNamed class (I would like to type the return of __invoke, replacing its actuel signature with something like public function __invoke(ContainerInterface $container, $requestedName, array $options = null): LogNamed )?
Can I create a LogNamedAbstract class hierarchy (is it possible to use the $option parameter, as a “token” to indicate which type of object - in the hierarchy - should be created and returned)?
Can I use parameter $option, as a “token” for direct injection into a new() returned by a construct inside a factory?
Put another way, how can I pass a configured $option parameter to a factory->__invoke(); from the calling code, using ServiceManager->get();, if possible?

That’s a lot of questions (I know)… :thinking:

Hmm: I’ve just seen that there’s a new $goServiceManager->build(‘ClassName’, $options) method, in ZF3 (coming from ZF2), where $options should be probably able to be used as the “token” to saying which real class instance from a classes hierarchy I want to make do create, or\and which new direct dependency injection(s) I want to use (I’ll test it tomorrow: I’m tired now).

The documentation of laminas-servicemanager includes this topic:

And also the migration guide:

Thank you, @froschdesign, for the links towards ZF2->ZF3 factories’s migration guide. Wow: the build method correctly passes the $option array as parameter to __invoke. Amho, ZF3 greatly simplifies the design pattern of the factory compared to ZF2!

Thanks to Zend\Laminas :slightly_smiling_face: .