Soroush Khosravi
Soroush Khosravi

Reputation: 917

Zend Framework 2 Override an existing Service?

I am using a zf2 module called GoalioRememberMe and now I want to override its service by my customized service. Or if it is not possible, I want to override the Module.php with my config. Is it possible?

In the Application module. I wrote this line in module.config.php:
'GoalioRememberMe\Service\RememberMe' => 'Application\Service\RememberMe'

Thanks in advance!

Upvotes: 6

Views: 2191

Answers (3)

dougB
dougB

Reputation: 509

Actually the service manager first runs a method "canonicalizeName()" which "normalizes" the names as follows:

  1. All _ / \ and - are stripped out
  2. The key is made lowercase

Thus both "GoalioRememberMe\Service\RememberMe" and "goaliorememberme_rememberme_service" become "goalioremembermeremembermeservice" (i.e. they're both the same), thus the error message.

The quickest way to override an existing service is to create a *local.php or *global.php file in the /config/autoload folder. (That folder is identified in config/application.config.php.) Any override files in this folder are process after modules are loaded. If you have duplicate service manager keys, the last one wins.

Upvotes: 0

Soroush Khosravi
Soroush Khosravi

Reputation: 917

As Jurian said, the service name is goaliorememberme_rememberme_service and it has been set in the getServiceConfig() method. So I wrote this code in the Module.php file in the Application Module:

$serviceManager->
            setAllowOverride(true)->
            setInvokableClass('goaliorememberme_rememberme_service', 'Application\Service\CustomRememberMe')->
            setAllowOverride(false);

And it replaced successfully with my customized service!
Thanks very much to Jurian for the big help!

Upvotes: 1

Jurian Sluiman
Jurian Sluiman

Reputation: 13558

This is exactly the reason it is recommended to name the service as the type of the object that is returned. The object GoalioRememberMe\Service\RememberMe is named goaliorememberme_rememberme_service in the service manager. You can check that here.

So the solution is simple, instead of this:

'GoalioRememberMe\Service\RememberMe' => 'Application\Service\RememberMe'

Write this

'goaliorememberme_rememberme_service' => 'Application\Service\RememberMe'

Upvotes: 7

Related Questions