M
M
magary42015-08-18 23:09:26
Zend Framework
magary4, 2015-08-18 23:09:26

What is the idea behind the getServiceLocatior/setServiceLocator methods?

Often seen in class

getServiceLocator() {
      return $this->serviceLocator;
}

What benefit can be derived from this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
Cat Anton, 2015-08-18
@magary4

If the question is specifically about the ServiceLocator in Zend Framework, then these methods provide access to the ServiceManager , which allows you to get other objects (services) of the application.
For example, there is a User class, and we want to access the service for authentication in it. This can be done like this:

namespace Application\Entity;

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class User implements ServiceLocatorAwareInterface
{
    protected $serviceLocator = null;

    public function __construct(ServiceLocatorInterface $serviceLocator) 
    {
        $this->setServiceLocator($serviceLocator);
    }

    public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
    {
        $this->serviceLocator = $serviceLocator;
        return $this;
    }

    public function getServiceLocator()
    {
        return $this->serviceLocator;
    }

    public function getAuthService()
    {
        return $this->getServiceLocator()->get('AuthService');
    }
}

The same can be written shorter using the trait:
namespace Application\Entity;

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\ServiceLocatorAwareTrait;

class User implements ServiceLocatorAwareInterface
{
    use ServiceLocatorAwareTrait;

    public function __construct(ServiceLocatorInterface $serviceLocator) 
    {
        $this->setServiceLocator($serviceLocator);
    }

    public function getAuthService()
    {
        return $this->getServiceLocator()->get('AuthService');
    }
}

Alternatively, Dependency Injection can be used .

A
Alexey Ukolov, 2015-08-18
@alexey-m-ukolov

Benefits of getters and setters
From here

A
Andrey Pavlenko, 2015-08-18
@Akdmeh

Usually it makes sense to additionally check the data, hide the actual data acquisition (we are not interested in the internal implementation and it can be changed at any time, but only the result is of interest).
By the way, there is an interesting solution in Yii2 in the Object class (if I'm not mistaken) - even if "magic" is used there, but it is quite logical and convenient. You need your own getter / setter - write it, and if it doesn't exist - use the magic method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question