0

I created a service layer AbcService in order to allow modules to access common lines of code. But I need to use database to extract values in my AbcService. So, I need to call getAbcTable() which calls $service->getServiceLocator(). When I try this, I get an error saying 'Call to undefined method getServiceLocator().

public function getAbcTable()
 {
     if (!$this->abcTable) {
         $sm = $this->getServiceLocator();
         $this->abcTable = $sm->get('Abc\Model\AbcTable');
     }
     return $this->abcTable;
 }
user2740957
  • 171
  • 2
  • 15

1 Answers1

3

You're trying to call a method that presumably doesn't exist. If you need AbcTable in your service, you should pass it in as a dependency.

Create a factory for your service that does this, in Module.php:

public function getServiceConfig()
{
    return array(
        'factories' => array(
            'AbcService' => function($sm) {
                $abcTable = $sm->get('Abc\Model\AbcTable');

                $abcService = new AbcService($abcTable);

                return $abcService;
            },
    );
}

and modify the constructor for your service to accept the table as a paramter:

class AbcService
{
    protected $abcTable;

    public function __construct($abcTable)
    {
        $this->abcTable = $abcTable;
    }

    // etc.
}

then, wherever you need AbcService, either inject it in, or grab it from the service locator:

public function indexAction()
{
    $abcService = $this->getServiceLocator()->get('AbcService');
}

and the service will have the table class in it.

Tim Fountain
  • 33,093
  • 5
  • 41
  • 69
  • I get a warning 'Missing argument 1 for __construct()', a notice saying 'undefined variable: chatTable' and call to undefined method getServiceLocator. I did exactly as you had suggested. – user2740957 Jul 02 '14 at 11:51
  • Sounds like what you are passing to the AbcService constructor is null, rather than the table object, but I'd need to see your code to be able to help more. Please edit your question to include this if you aren't able to solve it. – Tim Fountain Jul 02 '14 at 12:01
  • I think I have got over that problem now. I had 1 small query. How do I get baseUrl in Service Layer? As getRequestUri() can only be used in controller. – user2740957 Jul 03 '14 at 08:27