Search code examples
phpzend-framework2zend-framework3

How to access service locator object inside a controller in ZF3?


I am trying to access service locator object inside my controller but unable to do this.
I tried online help but most of them are following approach for ZF2

Previously Servicelocator access in zf2 was a breeze, I just had to do $this->getServiceLocator();

I have tried creating factory Class for my controller and Created createService method there but it says I have to implement __invoke() method too.

My Objective is to do something like this

public function getPropertyTable()
{
    if (!$this->PropertyTable) {
        $sm = $this->getServiceLocator();
        $this->PropertyTable = $sm->get('Application\Model\PropertyTable');
    }
    return $this->PropertyTable;
}


Can anyone provide me a complete steps to achieve this?

I have tried to implement almost all Answers related to Servicelocator before asking this question, so please help me before marking this as Duplicate or something, ignore the typos


Solution

  • Thanks everyone to tell me I am doing it the wrong way.
    Some more research on this topic helped me to get my issue resolved
    here is what I have done to solve it

  • Create Factory class for your Controller
    You have to create a factory class for your controller which will implement FactoryInterface of zend. in there you have to call

    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
     {
           return new ListController($container->get(PropertyInterface::class));
     }
    


    here I am passing PropertyInterface refrence which is implemented by my another table called Property Table in which I have given body to all my inteface functions for model
    like searchProperty()

  • Add factory class in config file module.config.php for your controller
    instructing config file to let our factory create the object for our controller

    'controllers' => [
                'factories' => [
                    // Update the following line:
                    Controller\ListController::class => Factory\ListControllerFactory::class,
                ],
            ],
    


  • Register your Model in config file
    You have to add new section for service manager and provide your model classes there.

    // Add this section:
            'service_manager' => [
                'aliases' => [
                    Model\PropertyInterface::class => Model\PropertyTable::class,
                ],
                'factories' => [
                    Model\PropertyTable::class => InvokableFactory::class,
                ],
            ],
    



  • Now only thing left is add functions in your PropertyInterface and Implentation in PropertyTable for them and then call them in your controller

    This Complete Steps for implementation Helped me in implementing the new flow.
    Thanks to community. You all are best.