Saeven
Saeven

Reputation: 2300

ZF2 - Possible to override a factory?

I've created a module that needs to send email, and have created a mail service in its getServiceConfig as a factory. Simple enough.

$transport = $this->getServiceLocator()->get('custom_module_mail_transport');
// use transport

In Module.php:

          'custom_module_mail_transport' => function($instance, $sm) {
                $b    = new \Zend\Mail\Transport\Smtp();
                $b->setOptions(
                    new \Zend\Mail\Transport\SmtpOptions(
                        array(
                            'host'              => 'smtp.isp.com',
                            'connection_class'  => 'login',
                            'port'              => 25,
                            'connection_config' => array(
                                'username' => 'abc',
                                'password' => 'def',
                            )
                        )
                    )
                );
                return $b;
            },

I would like for people to be able to roll their own though, implementing their own factories for that mail transport for the custom module. I mean, I could use config to pick up on password and such, but the plethora of transports would make this unfun.

Adding a 'custom_module_mail_transport' factory to the Application-level service config doesn't seem to do the trick. Goal is to let the user roll their own factory to override the one the module provides.

What's the best way to do this?

Thanks for helping me wrap my head around ZF2.

Upvotes: 0

Views: 456

Answers (1)

Jacob S
Jacob S

Reputation: 1701

Someone may have a better solution, but I think you could use a factory that allows for a user-defined class type implementing a common interface that you expect.

Excuse the meta-overview, but the user could:

  • Configure in the module-specific configuration a value for "custom_module_mail_transport_class" => "FQD\Of\My_Mail_Transport"
  • Your service locator can use a factory which:
  • Checks if the user's class_exists
  • Creates a new $passed_module_config['custom_module_mail_transport_class']()
  • Type checks for instanceof mailtransport_interface (or whatever you may name it)
  • If it is not the correct implementaion, either creates your standard class and/or generates an exception.

But then, I haven't really worked much with ZF2 yet.

Upvotes: 2

Related Questions