Guy Fawkes
Guy Fawkes

Reputation: 2441

Setting up ServiceManager with configuration files in Zend Framework 2

I have read ZF documentation about ServiceManager and think configuration (even in "config" php files) like

public function getServiceConfig()
  {
    return array(
      'invokables' => array(
        'my-foo' => 'MyModule\Foo\Bar',
      ),
    );
  }

is very long and verbose. And, if I have a lot of dependencies, I want to use some sort of automatic code-geneation for this task.

In Symfony, I can to just write YAML configs like this:

parameters:
    mailer.transport: sendmail

services:
    mailer:
        class:     Mailer
        arguments: ["%mailer.transport%"]
    newsletter_manager:
        class:     NewsletterManager
        calls:
            - [setMailer, ["@mailer"]]

And it automatically compiles to PHP code by Symfony. Are there some solution to do similar work for ZF2? I don't think everybody writes tones of DI code instead of real work.

Upvotes: 0

Views: 155

Answers (2)

Saeven
Saeven

Reputation: 2300

You generally will want to wire these in your module's configuration (e.g., module/Application/config/module.config.php).

The array syntax is shorter.

 return [
     'service_manager' => [
          'invokables' => [
               ...
           ],
      ],
 ];

Use ::class instead of class strings, it really cleans up the code, and makes it intuitive to invoke them with the SL throughout your app. Simply drop a 'use' statement at the top, and ::class away.

Don't sweat config if you are getting into ZF2. It's a pretty intuitive thing down the road, and though it may be a bit slower to wire components at first, once you get into it, you'll find ZF2 makes the very complex things easier than these other frameworks would; probably at the expense of making the easy things a bit more verbose.

ref: http://framework.zend.com/manual/current/en/modules/zend.service-manager.quick-start.html

Upvotes: 0

Tim Klever
Tim Klever

Reputation: 601

You can wire up the Zend\Config\Reader\Yaml to parse your configs, but they aren't going to be any more or less verbose, just a different format. If you prefer that format, feel free, but PHP arrays are exceedingly flexible and useful for config like this.

Upvotes: 1

Related Questions