Php Zend Framework 2:如何在自定义库中获取DBAdapter

Php Zend Framework 2:如何在自定义库中获取DBAdapter,php,zend-framework2,Php,Zend Framework2,在ZF2上的项目中,我正在创建我的自定义库vendor/TestVendor/TestLibrary/。 在这个库中,我想创建两个类:TestClass和TestClassTable。TestClass应该实例化我的自定义对象,TestClassTable应该处理数据库和表。 我需要在类TestClass表中使用DBAdapter来访问数据库和表 代码如下所示: 在模块索引控制器中,我从TestClass创建对象 类TestController扩展了AbstractActionControlle

在ZF2上的项目中,我正在创建我的自定义库vendor/TestVendor/TestLibrary/。 在这个库中,我想创建两个类:TestClass和TestClassTable。TestClass应该实例化我的自定义对象,TestClassTable应该处理数据库和表。 我需要在类TestClass表中使用DBAdapter来访问数据库和表

代码如下所示:

在模块索引控制器中,我从TestClass创建对象

类TestController扩展了AbstractActionController {

}

在自定义类vendor/TestVendor/TestLibrary/TestClass.php中,我创建了一些方法:

名称空间TestVendor\TestLibrary

类TestClass {

}

在TestClassTable类中,我想访问数据库

名称空间TestVendor\TestLibrary

使用Zend\Db\TableGateway\AbstractTableGateway

类TestClassTable扩展了AbstractTableGateway {

}

当然,尝试访问类TestClassTable中的服务定位器或数据库适配器会导致错误

看来我的方法错了


非常感谢。

您应该使用服务管理器将其注入到您的类中

服务管理器配置:

return array(
    'factories' => array(
         'MyClass' => function($sm) {
            $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
            $myClass = new \MyNamespace\MyClass($dbAdapter);
            // I would have a setter, and inject like that but
            // using the constructor is fine too
            //$myclass->setDbAdapter($dbAdapter);

            return $myClass;
        },
    )
)
现在,您可以在控制器中获取一个实例,并且已经为您注入了DB适配器:

SomeController.php

public function indexAction()
{
    $MyObject = $this->getServiceLocator()->get('MyClass');
}

您应该使用服务管理器将其注入到类中

服务管理器配置:

return array(
    'factories' => array(
         'MyClass' => function($sm) {
            $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
            $myClass = new \MyNamespace\MyClass($dbAdapter);
            // I would have a setter, and inject like that but
            // using the constructor is fine too
            //$myclass->setDbAdapter($dbAdapter);

            return $myClass;
        },
    )
)
现在,您可以在控制器中获取一个实例,并且已经为您注入了DB适配器:

SomeController.php

public function indexAction()
{
    $MyObject = $this->getServiceLocator()->get('MyClass');
}

如果您手动注入DBAdapter,那么您的代码是高度耦合的,使用服务管理器有助于实现这一点,但是您仍然将自己耦合到DBAdapter。根据您试图实现的目标,有多种方法可以将您的供应商代码与此分离。使用@Andrew建议的服务管理器查看数据映射器模式&适配器模式


注意:ZF2中供应商中的库应该是一个单独的项目,并通过composer包含。

如果手动注入DBAdapter,则代码是高度耦合的,使用服务管理器可以帮助您实现这一点,但是您仍然将自己耦合到DBAdapter。根据您试图实现的目标,有多种方法可以将您的供应商代码与此分离。使用@Andrew建议的服务管理器查看数据映射器模式&适配器模式


注意:ZF2中供应商的库应该是一个单独的项目,并通过composer包含。

看起来我的问题不太准确。看起来我的问题不太准确。
public function indexAction()
{
    $MyObject = $this->getServiceLocator()->get('MyClass');
}