我是Doctrine 2和ZF2的新手。
我的问题:如果我尝试访问{{1},我会转到实例化类myPage/bnk
的路由BnkController
和方法indexAction
方法从那里一切正常。
现在,当我在方法getEntityManager
中实例化类DataManager
然后我尝试在类indexAction
中调用getEntityManager
方法时,我得到DataManager
如果它全部在Fatal error: Call to a member function get() on a non-object
为什么当我尝试从课程BnkController
中的EntityManager
获取原则getServiceLocator
时,我收到此错误?
DataManager
的DataManager
class BnkController extends AbstractActionController
{
public function indexAction ()
{
$this->uploadCSVAction( "data/bnk.csv" );
}
public function uploadCSVAction ( $fileName )
{
$parseCSV = new CsvParser();
$dataManager = new DataManager();
// Transforms CSV into Array
$CSVData = $parseCSV->parseCSV( $fileName );
// Makes sure that we are only using the right transactions and no overlap is happening
$CSVData = $dataManager->validateTransactions($CSVData,$parseCSV);
$dataManager->saveCSVDataToDB( $CSVData );
}
/**
* @return \Doctrine\ORM\EntityManager
*/
protected function getEntityManager ()
{
/** @var \Doctrine\ORM\EntityManager $objectManager */
$objectManager = $this
->getServiceLocator()
->get( 'Doctrine\ORM\EntityManager' );
return $objectManager;
}
答案 0 :(得分:2)
当我尝试从类DataManager中的getServiceLocator获取doctrine EntityManager时,为什么会出现此错误
DataManager
不了解服务定位器或实体管理器。为什么?因为您是使用new
运算符创建的。
$dataManager = new DataManager(); // nothing injected or set
您需要确保使用工厂注入依赖项,然后通过服务定位器请求它们。
更新控制器以获取服务
$dataManager = $this->getServiceLocator()->get('MyModule\Service\DataManager');
创建一个新工厂以注入 EntityManager (而不是服务定位器)
namespace MyModule\Factory;
use MyModule\Service\DataManager;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\FactoryInterface;
class DataManagerFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
return new DataManager(
$serviceLocator->get('Doctrine\ORM\EntityManager')
);
}
}
向工厂注册服务经理
// MyModule\Module.php
public function getServiceConfig()
{
return array(
'factories' => array(
'MyModule\Service\DataManager'
=> 'MyModule\Factory\DataManagerFactory',
),
);
}
最后,给DataManager
一个构造函数,这样就可以注入EntityManager
use Doctrine\Common\Persistence\ObjectManager;
class DataManager
{
protected $objectManager;
public function __construct(ObjectManager $objectManager)
{
$this->objectManager = $objectManager;
}
protected function getEntityManager ()
{
return $this->objectManager;
}
}