I have written a custom service for my module. This service provides public static functions which should validate a given token.
Now i want to implement another public
Personally, I'd make the service a 'service' and put it in the ServiceManager. In addition I'd consider refactoring the code. Right now you have a dependency on the ObjectExists validator, which in turn depends on and entity repository, and that depends on the entity manager. It would be much simpler to compose the validator outside the service and inject it from a factory. That way, if you ever need to use a different validator, you just hand it a different one.
class ApiService
{
protected $validator;
public function isValid($apiKey)
{
// other code
$isValid = $this->exists($apiKey);
}
public function exists($apiKey)
{
return $this->getValidator()->isValid($apiKey);
}
public function setValidator(\Zend\Validator\AbstractValidator $validator)
{
$this->validator = $validator;
return $this;
}
public function getValidator()
{
return $this->validator;
}
}
In Module.php create the service as a factory method, or better still as a factory class, but that's left as an exercise for you :)
public function getServiceConfig()
{
return array(
'factories' => array(
'ApiService' => function($sm) {
$em = $sm->get('Doctrine\ORM\EntityManager');
$repo = $em->getRepository('Application\Entity\User');
$validator = new \DoctrineModule\Validator\ObjectExists($repo,
array('fields' => array('email')));
$service = new ApiService();
$service->setValidator($validator);
return $service;
},
),
);
}
Now if you need a different EntityManager, a different Entity repository, or even a whole different validator you only need to change a couple of lines above rather than having to delve into your services code.