Answer the question
In order to leave comments, you need to log in
What is the idea behind the getServiceLocatior/setServiceLocator methods?
Often seen in class
getServiceLocator() {
return $this->serviceLocator;
}
Answer the question
In order to leave comments, you need to log in
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');
}
}
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');
}
}
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 questionAsk a Question
731 491 924 answers to any question