Here is a Factory :
namespace Maintenance\Factory\View\Helper;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Maintenance\View\Helper\SousMenuContrat;
class SousMenuContratFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$realServiceLocator = $serviceLocator->getServiceLocator();
$maiContratService = $realServiceLocator->get(
'Maintenance\Service\Model\FMaiContratService'
);
return new SousMenuContrat(
$maiContratService
);
}
}
I have to write some PHPUnit tests, I began to do so :
public function testCreateService()
{
$this->mockDriver = $this->getMock('Zend\Db\Adapter\Driver\DriverInterface');
$this->mockConnection = $this->getMock('Zend\Db\Adapter\Driver\ConnectionInterface');
$this->mockDriver->expects($this->any())->method('checkEnvironment')->will($this->returnValue(true));
$this->mockDriver->expects($this->any())->method('getConnection')->will($this->returnValue($this->mockConnection));
$this->mockPlatform = $this->getMock('Zend\Db\Adapter\Platform\PlatformInterface');
$this->mockStatement = $this->getMock('Zend\Db\Adapter\Driver\StatementInterface');
$this->mockDriver->expects($this->any())->method('createStatement')->will($this->returnValue($this->mockStatement));
$this->adapter = new Adapter($this->mockDriver, $this->mockPlatform);
$this->sql = new Sql($this->adapter);
$mockTableGateway = $this->getMock('Zend\Db\TableGateway\TableGateway', array(), array(), '', false);
$maiContratTable = $this->getMockBuilder('Maintenance\Model\BDD\FMaiContratTable')
->setMethods(array())
->setConstructorArgs(array($mockTableGateway, $this->adapter, $this->sql))
->getMock();
$smMock = $this->getMockBuilder('Zend\ServiceManager\ServiceManager')
->setMethods(array('get'))
->getMock();
$smMock->expects($this->at(0))
->method('get')
->with('Maintenance\Service\Model\FMaiContratService')
->will($this->returnValue(new FMaiContratService($maiContratTable)));
$factory = new SousMenuContratFactory();
$runner = $factory->createService($smMock);
}
But I got some problems. This tells me :
Call to undefined method Mock_ServiceManager_3ed93deb::getServiceLocator()
What have I misunderstood ?
Thanks !
In your factory you call:
$realServiceLocator = $serviceLocator->getServiceLocator();
But you defined:
$smMock->expects($this->at(0))
->method('get')
The ServiceLocator passed to your factory usually does not have the method getServiceLocator because it already is the service locator. (Edit: Scratch that, PluginManagers do!) Instead use:
public function createService(ServiceLocatorInterface $serviceLocator)
{
$maiContratService = $serviceLocator->get(
'Maintenance\Service\Model\FMaiContratService'
);
return new SousMenuContrat(
$maiContratService
);
}
Edit: Plugin factories are another thing, here's the test code:
public function testCreateService()
{
$maiContractServiceMock = $this->getMockBuilder('Maintenance\Service\Model\FMaiContratService')
->disableOriginalConstructor()
->getMock();
// if you do something with FMaiContratService in the constructor of SousMenuContrat,
// mock more methods here
$smMock = $this->getMockBuilder('Zend\ServiceManager\ServiceManager')
->setMethods(array('get'))
->getMock();
$smMock->expects($this->at(0))
->method('get')
->with('Maintenance\Service\Model\FMaiContratService')
->will($this->returnValue($maiContractServiceMock));
$hpmMock = $this->getMockBuilder('Zend\View\HelperPluginManager')
->setMethods(array('getServiceLocator'))
->getMock();
$hpmMock->expects($this->any())
->method('getServiceLocator')
->will($this->returnValue($smMock));
$factory = new SousMenuContratFactory();
$runner = $factory->createService($hpmMock);
}
In this case, you need a mock of the plugin manager, returning another service locator if getServiceLocator is called. Désolé!
Related
I am running phpunit version 9.2 and I would like to know why my method is not covered in the phpunit coverage.
This is my class:
class Methods extends Template
{
const DISABLED_PAYMENT_METHODS_1 = 'free';
const DISABLED_PAYMENT_METHODS_2 = 'adyen_cc';
const DISABLED_PAYMENT_METHODS_3 = 'adyen_oneclick';
protected $paymentMethodList;
protected $storeManager;
protected $logger;
public function __construct(
Context $context,
PaymentMethodList $paymentMethodList,
StoreManagerInterface $storeManager,
LoggerInterface $logger,
array $data = []
) {
$this->paymentMethodList = $paymentMethodList;
$this->storeManager = $storeManager;
$this->logger = $logger;
parent::__construct($context, $data);
}
public function getPaymentMethods()
{
try {
$storeId = $this->storeManager->getStore()->getId();
$paymentList = $this->paymentMethodList->getActiveList($storeId);
$resultPayments = [];
foreach ($paymentList as $payment) {
if ($payment->getCode() !== self::DISABLED_PAYMENT_METHODS_1 &&
$payment->getCode() !== self::DISABLED_PAYMENT_METHODS_2 &&
$payment->getCode() !== self::DISABLED_PAYMENT_METHODS_3
) {
$resultPayments[] = $payment;
}
}
return $resultPayments;
} catch (Exception $e) {
$this->logger->error($e->getMessage());
return false;
}
}
}
and this is my test class:
class MethodsTest extends TestCase
{
private $model;
private function getSimpleMock($originalClassName)
{
return $this->getMockBuilder($originalClassName)
->disableOriginalConstructor()
->getMock();
}
public function setUp() : void
{
$context = $this->getSimpleMock(Context::class);
$paymentMethodList = $this->getSimpleMock(PaymentMethodList::class);
$storeManager = $this->getSimpleMock(StoreManagerInterface::class);
$logger = $this->getSimpleMock(LoggerInterface::class);
$this->model = new Methods(
$context,
$paymentMethodList,
$storeManager,
$logger,
[]
);
}
public function testGetPaymentMethods()
{
$stub = $this->createMock(Methods::class);
$stub->method('getPaymentMethods')
->willReturn([]);
try {
$stub->getPaymentMethods();
$this->fail("Expected exception!");
} catch (\Exception $error) {
$this->assertEquals("Expected exception!", $error->getMessage());
}
}
}
When I run the command to get the coverage. I am getting:
I am really curious why my test is not covered or at least the exception part ? Would you please share you ideas why ? and what can i do in order to fix this ? Right now I got a 29 % and I would like to get at least 60% coverage.
Thank you
On this line $stub = $this->createMock(Methods::class); you are creating a mock of the Methods class, so not actually testing the real class.
You will need to use the object you created in your setUp() method, and set up mock returns on the dependencies you passed in (perhaps converting some of them to be class properties).
You should test the real class, as example:
public function testGetPaymentMethods()
{
// define a payment
$paymentFreeCode = $this->createMock(Payment::class);
$paymentFreeCode->method('getcode')
->willReturn("free");
// define a payment
$payment = $this->createMock(Payment::class);
$payment->method('getcode')
->willReturn("invalid-code");
$paymentList = [
$paymentFreeCode,
$payment,
];
// define a store
$store = $this->createMock(Store::class);
$store->method('getId')
->willReturn("my-store-id");
// return store from the store manager
$this->storeManager->method('getStore')
->willReturn(myStore);
// return the payment list
$this->paymentMethodList->method('getActiveList')->with("my-store-id")
->willReturn($paymentList);
// call the real class instrumented with mocks
$paymentMethods = $this->model->getPaymentMethods();
$this->assertIsArray($paymentMethods);
$this->assertCount($paymentMethods, 1);
}
I created a View Helper :
class SousMenuContrat extends AbstractHelper
{
private $maiContratService;
public function __construct(
FMaiContratService $maiContratService,
) {
$this->maiContratService = $maiContratService;
}
public function __invoke($iMaiContratId, $sActive)
{
$oContrat = $this->maiContratService->selectById($iMaiContratId);
return $this->getView()->partial('maintenance/sousmenucontrat', array(
'oContrat' => $oContrat
));
}
}
So now I need to test it, with PHPUnit :
class SousMenuContratTest extends TestCase
{
private $myService;
public function setUp()
{
$maiContratService = $this->getMockBuilder('Maintenance\Service\Model\FMaiContratService')
->disableOriginalConstructor()
->getMock();
$oContrat = new FMaiContrat();
$stub = $this->returnValue($oContrat);
$maiContratService->expects($this->any())->method('selectById')->will($stub);
$this->myService = new SousMenuContrat(
$maiContratService
);
}
public function testInvoque()
{
$this->myService->__invoke(2, 'contrat');
}
}
But the test sends an error, because the test doesn't know :
$this->getView()->partial();
Thanks in advance :)
In your test, you need to mock the renderer returned by getView():
/** #var PhpRenderer|\PHPUnit_Framework_MockObject_MockObject $rendererMock */
$rendererMock = $this->getMockBuilder('Zend\View\Renderer\PhpRenderer')
->disableOriginalConstructor()
->getMock();
$rendererMock->expects($this->once())
->method("partial")
->with(array(
'maintenance/sousmenucontrat',
array('oContrat' => new FMaiContrat()),
));
$this->myService->setView($rendererMock);
Best solution would be to use the same FMaiContrat object you instantiate in setUp() in with(), but in this case, this works as well.
Edit: And the complete test code will look like this:
class SousMenuContratTest extends TestCase
{
private $myService;
public function setUp()
{
$maiContratService = $this->getMockBuilder('Maintenance\Service\Model\FMaiContratService')
->disableOriginalConstructor()
->getMock();
$oContrat = new FMaiContrat();
$stub = $this->returnValue($oContrat);
$maiContratService->expects($this->any())->method('selectById')->will($stub);
$this->myService = new SousMenuContrat(
$maiContratService
);
}
public function testInvoque()
{
/** #var PhpRenderer|\PHPUnit_Framework_MockObject_MockObject $rendererMock */
$rendererMock = $this->getMockBuilder('Zend\View\Renderer\PhpRenderer')
->disableOriginalConstructor()
->getMock();
$rendererMock->expects($this->once())
->method("partial")
->with(array(
'maintenance/sousmenucontrat',
array('oContrat' => new FMaiContrat()),
));
$this->myService->setView($rendererMock);
$this->myService->__invoke(2, 'contrat');
}
}
You can use the following setup if you want to just use ZF2 classes and then just mock your dependency in SousMenuContrat constructor
protected function setUp()
{
$maiContratService = $this->getMockBuilder('Maintenance\Service\Model\FMaiContratService')
->disableOriginalConstructor()
->getMock();
$oContrat = new FMaiContrat($maiContratService);
$stub = $this->returnValue($oContrat);
$maiContratService->expects($this->any())->method('selectById')->will($stub);
Doctype::unsetDoctypeRegistry();
$this->helper = new SousMenuContrat();
$this->renderer = new PhpRenderer;
$this->viewHelperManager = $this->renderer->getHelperPluginManager();
$config = new HelperConfig();
$config->configureServiceManager($this->viewHelperManager);
$this->helper->setView($this->renderer);
parent::setUp();
}
So I created a test service set :
class FMaiAffaireServiceTest extends TestCase
{
/**
* #var MyService
*/
private $myService;
private $typeaffaireTable;
private $mockDriver;
private $mockConnection;
private $mockPlatform;
private $mockStatement;
private $adapter;
private $sql;
public function setUp()
{
$this->mockDriver = $this->getMock('Zend\Db\Adapter\Driver\DriverInterface');
$this->mockConnection = $this->getMock('Zend\Db\Adapter\Driver\ConnectionInterface');
$this->mockDriver->expects($this->any())->method('checkEnvironment')->will($this->returnValue(true));
$this->mockDriver->expects($this->any())->method('getConnection')->will($this->returnValue($this->mockConnection));
$this->mockPlatform = $this->getMock('Zend\Db\Adapter\Platform\PlatformInterface');
$this->mockStatement = $this->getMock('Zend\Db\Adapter\Driver\StatementInterface');
$this->mockDriver->expects($this->any())->method('createStatement')->will($this->returnValue($this->mockStatement));
$this->adapter = new Adapter($this->mockDriver, $this->mockPlatform);
$this->sql = new Sql($this->adapter);
$mockTableGateway = $this->getMock('Zend\Db\TableGateway\TableGateway', array(), array(), '', false);
$maiAffaireTable = $this->getMockBuilder('Maintenance\Model\BDD\FMaiAffaireTable')
->setMethods(array())
->setConstructorArgs(array($mockTableGateway, $this->adapter, $this->sql))
->getMock();
$stub = $this->returnValue(new ResultSet());
$maiAffaireTable->expects($this->any())->method('listAffaires')->will($stub);
$this->myService = new FMaiAffaireService(
$maiAffaireTable
);
}
public function testListAffaires()
{
$this->myService->listAffaires(1,10);
}
}
My service looks like this, it is a call to my Zend Db function :
class FMaiAffaireService
{
private $maiAffaireTable;
public function __construct(
$maiAffaireTable,
) {
$this->maiAffaireTable = $maiAffaireTable;
}
public function listAffaires($iOffset, $iLimit) {
$aResults = $this->maiAffaireTable->listAffaires($iOffset, $iLimit);
return $aResults->toArray();
}
}
And here is the sample of my Zend DB function :
class FMaiAffaireTable
{
protected $tableGateway;
protected $adapter;
protected $sql;
public function __construct(
TableGateway $tableGateway,
Adapter $adapter,
Sql $sql
) {
$this->tableGateway = $tableGateway;
$this->adapter = $adapter;
$this->sql = $sql;
}
public function listAffaires($iOffset, $iLimit)
{
try {
$resultSet = $this->tableGateway->select(
function (Select $select) use (
$iOffset,
$iLimit
) {
$select->offset($iOffset);
$select->limit($iLimit);
}
);
return $resultSet;
} catch (\Exception $e) {
throw new \Exception($e);
}
}
}
And there is a big problem at the execution of PHPUnit :
1) Directories\FMaiAffaireServiceTest::testListAffaires reset() expects parameter 1 to be array, null given
I don't call reset() ANYWHERE ! That's the problem ... I think it's a PDO function but ... I'm a bit lost.
Thanks.
The problem is here
$stub = $this->returnValue(new ResultSet());
$maiAffaireTable->expects($this->any())->method('listAffaires')->will($stub);
A non-initialized ResultSet will not have a datasource, running toArray() on it (as you do in your service) will first try and reset the datasource, which will be null.
Try
$resultSet = new ResultSet();
$resultSet->initialize(array());
$stub = $this->returnValue($resultSet);
How can I test a forward in a controller with PHPUnit?
I have two simple modules (A and B), module A call the module B using a forward.
here is a simple code that not work :
ModuleA
class ModuleAController extends AbstractRestfulController
{
protected $em;
public function setEntityManager(EntityManager $em)
{
$this->em = $em;
}
public function getEntityManager()
{
if (null === $this->em) {
$this->em
$this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
}
return $this->em;
}
public function getList()
{
$data = array('message' => 'passed by module A');
$forward = $this->forward()->dispatch('ModuleB\Controller\ModuleB');
$data['Message'] = $forward->getVariable('Message');
return new JsonModel($data);
}
}
ModuleB
class ModuleBController extends AbstractRestfulController
{
public function setEntityManager(EntityManager $em)
{
$this->em = $em;
}
public function getEntityManager()
{
if (null === $this->em) {
$this->em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
}
}
public function getList()
{
$data = array('Message'=>'passed by module B');
return new JsonModel($data);
}
}
And this is a test code :
class ModuleAControllerTest extends AbstractHttpControllerTestCase
{
protected $controller;
protected $request;
protected $response;
protected $routeMatch;
protected $event;
protected function setUp()
{
$serviceManager = Bootstrap::getServiceManager();
$this->controller = new ModuleAController();
$this->request = new Request();
$this->routeMatch = new RouteMatch(array());
$this->event = new MvcEvent();
$config = $serviceManager->get('Config');
$routerConfig = isset($config['router']) ? $config['router'] : array();
$router = HttpRouter::factory($routerConfig);
$this->event->setRouter($router);
$this->event->setRouteMatch($this->routeMatch);
$this->controller->setEvent($this->event);
$this->controller->setServiceLocator($serviceManager);
}
public function testModuleAControllerCanBeAccessed()
{
$result = $this->controller->dispatch($this->request);
$response = $this->controller->getResponse();
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals(200, 1+99+100);
}
}
And this is the error message :
There was 1 error:
1) ModuleATest\Controller\ModuleAControllerTest::testModuleAControllerCanBeAccessed
Zend\ServiceManager\Exception\ServiceNotCreatedException: An exception was raised while creating "forward"; no instance returned
....
Caused by
Zend\ServiceManager\Exception\ServiceNotCreatedException: Zend\Mvc\Controller\Plugin\Service\ForwardFactory requires that the application service manager has been injected; none found
....
FAILURES!
Tests: 1, Assertions: 0, Errors: 1.
Is there any way to make this code work ??Any idea ??
Thank you.
I have not created mock for plugins yet. I don't know how set new plugin to controller. But mock will be like it.
PHPunit test file
public function testControllerWithMock()
{
/* Result from ModuleBController method getList() */
$forwardResult = new JsonModel(array('Message'=>'passed by module B'));
/* Create mock object for forward plugin */
$forwardPluginMock = $this->getMockBuilder('\Zend\Mvc\Controller\Plugin\Forward')
->disableOriginalConstructor()
->getMock();
$forwardPluginMock->expects($this->once())
->method('dispatch') /* Replace method dispatch in forward plugin */
->will($this->returnValue($forwardResult)); /* Dispatch method will return $forwardResult */
/* Need register new plugin (made mock object) */
$controller->setPluginManager(); /* ??? Set new plugin to controller */
I'm thinking how decide it.
Ok, try it.
$controller->getPluginManager()->injectController($forwardPluginMock);
I don't write PHPUnit tests for controllers. Because controllers must return a view and best solution using Selenium for testing view. I usually use PHPUnitSelenium tests for testing it.
I have a problem with unit testing of my own SessionManager service. I don't have errors in unit tests but session isn't created in database and i can't write to storage. Here is my code:
SessionManagerFactory:
namespace Admin\Service;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\ServiceManager;
use Zend\Session\SaveHandler\DbTableGatewayOptions as SessionDbSavehandlerOptions;
use Zend\Session\SaveHandler\DbTableGateway;
use Zend\Session\Config\SessionConfig;
use Zend\Session\SessionManager;
use Zend\Db\TableGateway\TableGateway;
class SessionManagerFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
return $this;
}
public function setUp(ServiceManager $serviceManager)
{
$sessionOptions = new SessionDbSavehandlerOptions();
$sessionOptions->setDataColumn('data')
->setIdColumn('id')
->setModifiedColumn('modified')
->setLifetimeColumn('lifetime')
->setNameColumn('name');
$dbAdapter = $serviceManager->get('Zend\Db\Adapter\Adapter');
$sessionTableGateway = new TableGateway('zf2_sessions', $dbAdapter);
$sessionGateway = new DbTableGateway($sessionTableGateway, $sessionOptions);
$config = $serviceManager->get('Configuration');
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions($config['session']);
$sessionManager = new SessionManager($sessionConfig);
$sessionManager->setSaveHandler($sessionGateway);
return $sessionManager;
}
}
GetServiceConfig() method from Module.php in Admin namespace:
public function getServiceConfig()
{
return array(
'factories' => array(
'Zend\Authentication\Storage\Session' => function($sm) {
return new StorageSession();
},
'AuthService' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$authAdapter = new AuthAdapter($dbAdapter, 'zf2_users', 'email', 'password');
$authService = new AuthenticationService();
$authService->setAdapter($authAdapter);
$authService->setStorage($sm->get('Zend\Authentication\Storage\Session'));
return $authService;
},
'SessionManager' => function($serviceManager){
$sessionManager = new SessionManagerFactory();
return $sessionManager->setUp($serviceManager);
}
)
);
}
And setUp() mehod from unit test file:
protected function setUp()
{
$bootstrap = \Zend\Mvc\Application::init(include 'config/app.config.php');
$this->controller = new SignController;
$this->request = new Request;
$this->routeMatch = new RouteMatch(array('controller' => 'sign'));
$this->event = $bootstrap->getMvcEvent();
// Below line should start session and storage it in Database.
$bootstrap->getServiceManager()->get('SessionManager')->start();
// And this line should add test variable to default namespace of session, but doesn't - blow line is only for quick test. I will write method for test write to storage.
Container::getDefaultManager()->test = 12;
$this->event->setRouteMatch($this->routeMatch);
$this->controller->setEvent($this->event);
$this->controller->setEventManager($bootstrap->getEventManager());
$this->controller->setServiceLocator($bootstrap->getServiceManager());
}
How to test this service and why session aren't created?
I think you've misunderstood the Factory pattern. Your factory should look like the following. The separate setUp method is NEVER called anywhere as far as I can tell. You don't call it manually anywhere.
class SessionManagerFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$sessionOptions = new SessionDbSavehandlerOptions();
$sessionOptions->setDataColumn('data')
->setIdColumn('id')
->setModifiedColumn('modified')
->setLifetimeColumn('lifetime')
->setNameColumn('name');
$dbAdapter = $serviceManager->get('Zend\Db\Adapter\Adapter');
$sessionTableGateway = new TableGateway('zf2_sessions', $dbAdapter);
$sessionGateway = new DbTableGateway($sessionTableGateway, $sessionOptions);
$config = $serviceManager->get('Configuration');
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions($config['session']);
$sessionManager = new SessionManager($sessionConfig);
$sessionManager->setSaveHandler($sessionGateway);
return $sessionManager;
}
}
All the following code works for me. I think you are missing some other things but the above should fix it. Look for the SEE ME comments below. Also, add an onBootstrap method to your Module.php like I have below and make sure to call the $sessionManager = $serviceManager->get( 'SessionManager' ); in your case so that your SessionFactory is actually called. You already call it in your setup() function in the unit test but if you call it in the module you won't have to manually call it yourself.
In application.config I have this
'session' => array(
'name' => 'PHPCUSTOM_SESSID',
'cookie_lifetime' => 300, //1209600, //the time cookies will live on user browser
'remember_me_seconds' => 300, //1209600 //the time session will live on server
'gc_maxlifetime' => 300
)
'db' => array(
'driver' => 'Pdo_Sqlite',
'database' => '/tmp/testapplication.db'
),
My session factory is very similar but I have one extra line of code. Look for the comment.
use Zend\ServiceManager\FactoryInterface,
Zend\ServiceManager\ServiceLocatorInterface,
Zend\Session\SessionManager,
Zend\Session\Config\SessionConfig,
Zend\Session\SaveHandler\DbTableGateway as SaveHandler,
Zend\Session\SaveHandler\DbTableGatewayOptions as SaveHandlerOptions,
Zend\Db\Adapter\Adapter,
Zend\Db\TableGateway\TableGateway;
class SessionFactory
implements FactoryInterface
{
public function createService( ServiceLocatorInterface $sm )
{
$config = $sm->has( 'Config' ) ? $sm->get( 'Config' ) : array( );
$config = isset( $config[ 'session' ] ) ? $config[ 'session' ] : array( );
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions( $config );
$dbAdapter = $sm->get( '\Zend\Db\Adapter\Adapter' );
$sessionTableGateway = new TableGateway( 'sessions', $dbAdapter );
$saveHandler = new SaveHandler( $sessionTableGateway, new SaveHandlerOptions() );
$manager = new SessionManager();
/******************************************/
/* SEE ME : I DON'T SEE THE LINE BELOW IN YOUR FACTORY. It probably doesn't matter though.
/******************************************/
$manager->setConfig( $sessionConfig );
$manager->setSaveHandler( $saveHandler );
return $manager;
}
In one of my modules I have the following
public function onBootstrap( EventInterface $e )
{
// You may not need to do this if you're doing it elsewhere in your
// application
/* #var $eventManager \Zend\EventManager\EventManager */
/* #var $e \Zend\Mvc\MvcEvent */
$eventManager = $e->getApplication()->getEventManager();
$serviceManager = $e->getApplication()->getServiceManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach( $eventManager );
try
{
//try to connect to the database and start the session
/* #var $sessionManager SessionManager */
$sessionManager = $serviceManager->get( 'Session' );
/******************************************/
/* SEE ME : Make sure to start the session
/******************************************/
$sessionManager->start();
}
catch( \Exception $exception )
{
//if we couldn't connect to the session then we trigger the
//error event
$e->setError( Application::ERROR_EXCEPTION )
->setParam( 'exception', $exception );
$eventManager->trigger( MvcEvent::EVENT_DISPATCH_ERROR, $e );
}
}
}
This is my getServiceConfigMethod
public function getServiceConfig()
{
return array(
'factories' => array(
'Session' => '\My\Mvc\Service\SessionFactory',
'\Zend\Db\Adapter\Adapter' => '\Zend\Db\Adapter\AdapterServiceFactory'
)
);
}
I'm using sqllite at the moment so the table has to exist in your sqllite file already.
If you're using mysql, it should exist in that database too and you should change your db settings in the application.config.php file.