ZF2 – Service Manager – Using factories in a controller

One of my pain points, was trying to call a factory from the controller using the magic __get method, whilst using an alias.

I had setup a service factory, called “pcms” that I wanted to call via the controller:

return array(
    'service_manager' => array(
        'factories' => array(
            'pcms' => function() {
                return new PCMSService(
                    PCMS_SITE_ID,
                    array( ... )
                );
            }
        ),
    ),
);

in my controller, I’d planned on using:

$this->pcms->{functionnamehere}(...);

If I had used an alias in my config, It wouldn’t work:

return array(
    'service_manager' => array(
        'factories' => array(
            'PCMSService' => function() {
                return new PCMSService(
                    PCMS_SITE_ID,
                    array( ... )
                );
            }
        ),
        'aliases' => array(
            'pcms' => 'PCMSService',
        ),
    ),
);

Forego the alias, and simply name the factory whatever you want.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s