Reputation: 14532
In the album example of the Zend Framework 2 User Guide the model is configured like this:
<?php
namespace Album;
// Add these import statements:
use Album\Model\Album;
use Album\Model\AlbumTable;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
class Module
{
// getAutoloaderConfig() and getConfig() methods here
// Add this method:
public function getServiceConfig()
{
return array(
'factories' => array(
'Album\Model\AlbumTable' => function($sm) {
$tableGateway = $sm->get('AlbumTableGateway');
$table = new AlbumTable($tableGateway);
return $table;
},
'AlbumTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Album());
return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
}
The variable $sm
is a Zend\ServiceManager\ServiceManager
object. But how/when/where is it created/initialized?
EDIT:
What I want to know, is: How/where does $sm
get its value (and become a ServiceManager object).
Upvotes: 1
Views: 894
Reputation: 11447
When you retrieve a service from a service manager, if it's a factory, it passes an instance of itself as the first parameter to whichever callable is responsible for creating the service, that will usually be either a closure (as in your example), or the createService method of a factory class.
This is done, in the case of factories, by the code here https://github.com/zendframework/zf2/blob/master/library/Zend/ServiceManager/ServiceManager.php#L859
Basically, in your module you're telling the ServiceManager that those services are created by calling the closures you provided. When you ask the ServiceManager to get()
one of them the first time, it'll determine it's a factory (it was supplied in the factories key in config), then figure out if it's a closure or an instance of FactoryInterface (a factory class), and finally call it appropriately to instantiate your service.
Upvotes: 1