Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a factory in zend framework 2?

in my Module.php i have the fallowing methods that i would like to move them in a factory class so that i wont clutter the Module class:

public function getControllerConfig()
{
    return array(
        'factories' => array(
            'account-index' => function ($controllerManager) {
                $serviceManager = $controllerManager->getServiceLocator();
                $accountService = $serviceManager->get('account-service');

                return new Controller\IndexController($accountService);
            }
        )
    );
}

public function getServiceConfig()
{
    return array(
        'factories' => array(
            'account-service' => function ($serviceManages) {
                return new Service\Account;
            }
        )
    );
}

right now i have:

and where shall i put this factory class, maybe in a Factory folder?

any ideas?

like image 665
Patrioticcow Avatar asked Sep 18 '13 06:09

Patrioticcow


People also ask

What is Factory in Zend Framework?

The Factory¶ Storing the configuration will be done to one file. The factory is not aware of merging two or more configurations and will not store it into multiple files. If you want to store particular configuration sections to a different file you should separate it manually.

Which command is used to install Zend Framework 2?

The command: composer create-project -n -sdev zendframework/skeleton-application path/to/install always create a ZendFramework 3 app is their is a command to create a project of zendfrmaework 2.


1 Answers

I usually put my factories into ../module/yourmodule/src/yourmodule/Factory.

in your ../module/yourmodule/config/module.config.php you then have to configure your service_manager like so:

'service_manager' => array(
   'factories' => array(
      'yourfactory' => 'yourmodule\Factory\yourfactory',
   ),
),

in yourfactory.php You then have to implent the FactoryInterface and set the service locator. Once you done this you should be able to call the service the usual way for controllers, forms etc.

namespace Application\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class yourfactory implements FactoryInterface
{

private $config;

private $serviceLocator;

public function createService(ServiceLocatorInterface $serviceLocator)
{
    return $servicelocator->get('Your\Service');
}

After that you can just define functions in your yourfactory.php. In your Controller you call functions like so $serviceManager->get('yourfactory')->yourfunction(yourarguments);

like image 80
cptnk Avatar answered Nov 01 '22 08:11

cptnk