Eremite Eremite - 5 months ago 28
PHP Question

Service locator in Zend Framework 2

In controller I create and use my model so

public function getAlbumTable()
if (!$this->albumTable) {
$sm = $this->getServiceLocator();
$this->albumTable = $sm->get('Album\Model\AlbumTable');
return $this->albumTable;

How do I use this global Service Locator in another place of my project, for example, in the other model, and not only in any controller?

–°onfiguration of the connection to the database is defined in the file: my_project/config/autoload/global.php

Thank you.


Decided. So. For solving the task of classes of models must implement the interface ServiceLocatorAwareInterface. So injection ServiceManager will happen in your model automatically. See the previous example.

For forms and other objects of your application suitable method proposed here You can to create a base class form extends BaseForm and implements ServiceManagerAwareInterface, from which you will inherit its forms in the application.

namespace Common\Form;

use Zend\Form\Form as BaseForm;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;

class Form extends BaseForm implements ServiceManagerAwareInterface
     * @var ServiceManager
    protected $serviceManager;

     * Init the form
    public function init()

     * @param ServiceManager $serviceManager
     * @return Form
    public function setServiceManager(ServiceManager $serviceManager)
        $this->serviceManager = $serviceManager;

        // Call the init function of the form once the service manager is set

        return $this;

To injection of the object of the ServiceManager was automatically in the file module.config.php in section service_manager you need to write

'invokables' => array(
    'Album\Form\AlbumForm' => 'Album\Form\AlbumForm',

Then in your controller, you can create a form so

$form = $this->getServiceLocator()->get('Album\Form\AlbumForm');

The form will contain an object ServiceManager, which will allow other dependencies.

Thanks all for your help.