2013-03-21 47 views
1

在Zend框架2用户的相册示例性引导的模型被配置是这样的:Zend Framework 2用户指南中初始化的ServiceManager对象在哪里?

<?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); 
       }, 
      ), 
     ); 
    } 
} 

可变$smZend\ServiceManager\ServiceManager对象。但是,如何/何时/何地创建/初始化?

编辑:

我想知道的是:如何/在哪里呢$sm得到它的值(和成为的ServiceManager对象)。

+0

我会等待来自ZF2,离散事件之一的答案,但我的假设是这条线:https://github.com/zendframework/zf2/blob/master/library/Zend/ServiceManager/ServiceManager。 PHP#L737 – Sam 2013-03-21 11:43:37

+0

如果您正在使用的应用程序框架,它是由'应用程序初始化::实例化()'这里 - > https://github.com/zendframework/zf2/blob/master/library/Zend/Mvc/Application .php#L236 – Crisp 2013-03-21 12:29:31

+0

谢谢你的回复!我还没有得到,它如何工作。我只是试图制定我的问题exacter,s。编辑。 – automatix 2013-03-21 12:56:04

回答

1

当您从服务管理器中检索服务时,如果它是一个工厂,它将它自己的一个实例作为第一个参数传递给负责创建该服务的可调用对象,这通常是闭包(就像在你的例如)或工厂类的createService方法。

这样做,在工厂的情况下,这里的代码https://github.com/zendframework/zf2/blob/master/library/Zend/ServiceManager/ServiceManager.php#L859

基本上,你的模块中你告诉的ServiceManager,这些服务是通过调用您提供的封闭创建。当你问的ServiceManager他们的get()一个第一次,它会确定这是一个工厂(这是在配置工厂键提供),然后弄清楚,如果它是一个封闭或FactoryInterface(工厂类)的实例,最后调用它来实例化你的服务。

+0

感谢您的意见和答案!我想,我卡住了......我试着调试应用程序,特别是'ServiceManager#createFromFactory()',但找不到点,$ sm'获取它的值。 ZF2很难调试,因此很难学习/不支持(无论如何)。如果没有太多的努力,你可以(或别人)一步一步地描述整个链到代码中的位置,其中'$ sm'被初始化并获得值。就像一个评论堆栈跟踪。这将非常棒。非常感谢您提前! – automatix 2013-03-21 15:33:35

+3

是@Sam在你的OP连接线是在$ SM获取其值,该行'$实例= call_user_func($调用,这$,$ CNAME,$ RNAME);'其中第二PARAM'$ this'是传递给'call_user_func'的'ServiceManager'实例成为您收到的作为第一个参数的'$ sm'实例 – Crisp 2013-03-21 15:46:11