How to create a service layer in zend framwork two? - zend-framework2

I need to create a service layer for Zend framework two controller functions in order to decouple the services from controllers.

You're going to need to use the ServiceManager (SM) in order to make this work properly.
This is just an example of how I have done it:
In your ModuleName/src/ModuleName/ create a folder named Service and create your ExampleService.php, Example:
namespace ModuleName\Service;
class ExampleService
{
public function SomeFunctionNameHere()
{
echo 'Hello World';
}
}
Now edit your Module.php and add the Service Layer to your invokables, IE:
public function getServiceConfig()
{
return array(
'invokables' => array(
'ModuleName\Service\ExampleService' => 'ModuleName\Service\ExampleService',
),
);
}
Now edit your ModuleNameController.php
protected $service_example;
public function indexAction()
{
$service = $this->getServiceExample()->SomeFunctionNameHere();
}
private function getServiceExample()
{
if (!$this->service_example) {
$this->service_example = $this->getServiceLocator()->get('ModuleName\Service\ExampleService');
}
return $this->service_example;
}
This should get you started.

Depending on the functionality you are looking for from your service, you might be able to create a custom Controller Plugin. For example, here's a custom controller plugin I wrote to get a user's access level.
Application/Controller/Plugin/GetAccessLevel.php
namespace Application\Controller\Plugin;
use Zend\Mvc\Controller\Plugin\AbstractPlugin;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
class GetAccessLevel extends AbstractPlugin implements ServiceLocatorAwareInterface
{
/**
* Set the service locator.
*
* #param ServiceLocatorInterface $serviceLocator
* #return GetAccessLevel
*/
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
return $this;
}
/**
* Get the service locator.
*
* #return \Zend\ServiceManager\ServiceLocatorInterface
*/
public function getServiceLocator()
{
return $this->serviceLocator;
}
/**
* Takes an array of role objects and returns access level
*
* #param array of MyModule\Entity\Role objects
* #return int Access Level
*/
public function __invoke(array $roles)
{
// Default access level
$accesslevel = 0;
// Get Service Locator for view helpers
$controllerPluginManager = $this->getServiceLocator();
// Get application service manager
$serviceManager = $controllerPluginManager->getServiceLocator();
// Get application config
$config = $serviceManager->get('Config');
// Get the role associated with full access from config
$fullAccessRole = $config['appSettings']['full_access_role'];
// Does user have the role for full access?
foreach ($roles as $roleObject) {
if($roleObject->getName() == $fullAccessRole) {
$accesslevel = 1;
break;
}
}
// Return access level
return $accesslevel;
}
}
Then add the plugin to the configuration.
./module/Application/config/module.config.php
'controller_plugins' => array(
'invokables' => array(
'getAccessLevel' => 'Application\Controller\Plugin\GetAccessLevel'
)
),
Now every controller will have access to this plugin.
Some Controller
public function someAction() {
$accessLevel = $this->getAccesslevel(array('User Role Entities Go Here'));
}

Related

Symfony 5.4 with OAuth Keycloak connect Error must implement AuthenticatorInterface

I'm trying to implement an OAuth connection with Keycloak on Symfony 5.4, when I display a page of my application, all works fine, I have the keycloak login page, but after validate, I have this error :
Argument 1 passed to Symfony\Component\Security\Http\Authenticator\Debug\TraceableAuthenticator::__construct() must implement interface Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface, instance of App\Security\KeycloakAuthenticator given, called in /var/www/oauth-symfony/vendor/symfony/security-http/Authenticator/Debug/TraceableAuthenticatorManagerListener.php on line 60
Obviously I tried to add implements AuthenticatorInterface I hadd to add authenticate() and createToken() methods, but even with that the implementations still not works.
KeycloakAuthenticator.php
<?php
namespace App\Security;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use KnpU\OAuth2ClientBundle\Security\Authenticator\SocialAuthenticator;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
/**
* Class KeycloakAuthenticator
*/
class KeycloakAuthenticator extends SocialAuthenticator
{
/**
* ClientRegistry: the OAuth client manager
* EntityManagerInterface: to read/write in database
* RouterInterface: read a route/URL
*/
private $clientRegistry;
private $em;
private $router;
public function __construct(
ClientRegistry $clientRegistry,
EntityManagerInterface $em,
RouterInterface $router
)
{
$this->clientRegistry = $clientRegistry;
$this->em = $em;
$this->router = $router;
}
public function start(Request $request, \Symfony\Component\Security\Core\Exception\AuthenticationException $authenticationException = null): RedirectResponse
{
return new RedirectResponse(
'/oauth/login', // might be the site, where users choose their oauth provider
Response::HTTP_TEMPORARY_REDIRECT
);
}
public function supports(Request $request): ?bool
{
return $request->attributes->get('_route') === 'oauth_check';
}
public function getCredentials(Request $request)
{
return $this->fetchAccessToken($this->getKeycloakClient());
}
public function getUser($credentials, \Symfony\Component\Security\Core\User\UserProviderInterface $userProvider)
{
$keycloakUser = $this->getKeycloakClient()->fetchUserFromToken($credentials);
//existing user ?
$existingUser = $this
->em
->getRepository(User::class)
->findOneBy(['keycloakId' => $keycloakUser->getId()]);
if ($existingUser) {
return $existingUser;
}
// if user exist but never connected with keycloak
$email = $keycloakUser->getEmail();
/** #var User $userInDatabase */
$userInDatabase = $this->em->getRepository(User::class)
->findOneBy(['email' => $email]);
if($userInDatabase) {
$userInDatabase->setKeycloakId($keycloakUser->getId());
$this->em->persist($userInDatabase);
$this->em->flush();
return $userInDatabase;
}
//user not exist in database
$user = new User();
$user->setKeycloakId($keycloakUser->getId());
$user->setEmail($keycloakUser->getEmail());
$user->setRoles(['ROLE_USER']);
$this->em->persist($user);
$this->em->flush();
return $user;
}
public function onAuthenticationFailure(Request $request, \Symfony\Component\Security\Core\Exception\AuthenticationException $exception)
{
$message = strtr($exception->getMessageKey(), $exception->getMessageData());
return new Response($message, Response::HTTP_FORBIDDEN);
}
public function onAuthenticationSuccess(Request $request, \Symfony\Component\Security\Core\Authentication\Token\TokenInterface $token, string $providerKey)
{
// change "app_homepage" to some route in your app
$targetUrl = $this->router->generate('dashboard');
return new RedirectResponse($targetUrl);
}
/**
* #return \KnpU\OAuth2ClientBundle\Client\Provider\KeycloakClient
*/
private function getKeycloakClient()
{
return $this->clientRegistry->getClient('keycloak');
}
}
security.yml
security:
enable_authenticator_manager: true
password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
providers:
app_user_provider:
entity:
class: App\Entity\User
property: email
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
lazy: true
provider: app_user_provider
entry_point: form_login
form_login:
login_path: oauth_login
custom_authenticator: App\Security\KeycloakAuthenticator
access_control:
# - { path: ^/admin, roles: ROLE_ADMIN }
# - { path: ^/profile, roles: ROLE_USER }
- { path: ^/dashboard, roles: ROLE_USER }
OAuthController.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Annotation\Route;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use KnpU\OAuth2ClientBundle\Client\Provider\KeycloakClient;
class OAuthController extends AbstractController
{
/**
* #Route("/oauth/login", name="oauth_login")
*/
public function index(ClientRegistry $registry): RedirectResponse
{
/**#var KeycloakClient $client */
$client = $registry->getClient('keycloak');
return $client->redirect();
}
/**
* #Route("/oauth/callback", name="oauth_check")
*/
public function check(){}
}
You need replace the class to extend by OAuth2Authenticator 1.
Add the typing ": ?Response" on onAuthenticationSuccess and onAuthenticationFailure
And create the function "authenticate" to return PassportInterface

ZF FactoryInterface - using options parameter for configuring loading dependencies

I am wondering about the best practices for loading complex objects.
To begin with, i'm going to outline some boilerplate before getting to the problem.
Assume the following: A simple domain model Client is loaded using a tablegateway, with factories used at every stage to inject dependencies:
namespace My\Model\Client;
class Client implements InputFilterProviderInterface
{
/**#var integer*/
protected $id;
/**#var InputFilter*/
protected $inputFilter;
/**#var Preferences */
protected $preferences;
/**#var Orders*/
protected $orders;
/**#var Contacts*/
protected $contacts;
}
A factory for this Client object:
namespace My\Model\Client;
class ClientFactory implements FactoryInterface
{
public function($container, $requestedName, $options)
{
$client = new Client();
$client->setInputFilter($container->get('InputFilterManager')->get('ClientInputFilter'));
return $client;
}
}
Next the mapper factory, which uses a TableGateway:
namespace My\Model\Client\Mapper;
class ClientMapperFactory implements FactoryInterface
{
public function __invoke($container, $requestedName, $options)
{
return new ClientMapper($container->get(ClientTableGateway::class));
}
}
The TableGatewayFactory:
namespace My\Model\Client\TableGateway
class ClientTableGatewayFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$hydrator = new ArraySerialisable();
$rowObjectPrototype = $container->get(Client::class);
$resultSet = new HydratingResultSet($hydrator, $rowObjectPrototype);
$tableGateway = new TableGateway('clients', $container->get(Adapter::class), null, $resultSet);
return $tableGateway;
Note the use of a HydratingResultset to return fully formed Client objects from the ResultSet.
This all works nicely.
Now the Client object has several related objects as properties, so whilst using the HydratingResultSet, i'm going to add an AggregateHydrator to load them:
class ClientTableGatewayFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
**$hydrator = $container->get('HydratorManager')->get(ClientHydrator::class);**
$rowObjectPrototype = $container->get(Client::class);
$resultSet = new HydratingResultSet($hydrator, $rowObjectPrototype);
$tableGateway = new TableGateway('clients', $container->get(Adapter::class), null, $resultSet);
return $tableGateway;
}
Finally, the Clients hydrator factory:
class ClientHydratorFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
//base ArraySerializable for Client object hydration
$arrayHydrator = new ArraySerializable();
$arrayHydrator->addStrategy('dateRegistered', new DateTimeStrategy());
$aggregateHydrator = new AggregateHydrator();
$aggregateHydrator->add($arrayHydrator);
$aggregateHydrator->add($container->get('HydratorManager')->get(ClientsAddressHydrator::class));
$aggregateHydrator->add($container->get('HydratorManager')->get(ClientsOrdersHydrator::class));
$aggregateHydrator->add($container->get('HydratorManager')->get(ClientsPreferencesHydrator::class));
$aggregateHydrator->add($container->get('HydratorManager')->get(ClientsContactsHydrator::class));
return $aggregateHydrator;
}
}
... with the gist of the above hydrators being like:
class ClientsAddressHydrator implements HydratorInterface
{
/** #var AddressMapper */
protected $addressMapper;
public function __construct(AddressMapper $addressMapper){
$this->addressMapper = $addressMapper;
}
public function extract($object){return $object;}
public function hydrate(array $data, $object)
{
if(!$object instanceof Client){
return;
}
if(array_key_exists('id', $data)){
$address = $this->addressMapper->findClientAddress($data['id']);
if($address instanceof Address){
$object->setAddress($address);
}
}
return $object;
}
}
Finally we're at the issue. The above works perfectly and will load quite cleanly a Client object with all the related objects fully formed. But i have some resources where the entire object graph is not needed - for instance, when viewing a table of all clients - there is no need for any more information to be loaded.
So i've been thinking of ways of using the factories to choose which dependencies to include.
Solution 1
A factory for each use case. If only the Client data is needed (with no dependencies), then create a series of factories ie ClientFactory, SimpleClientFactory, ComplexClientFactory, ClientWithAppointmentsFactory etc. Seems redundant and not very reusable.
Solution 2
Use the options param defined in the FactoryInterface to pass "loading" options to the hydrator factory, eg:
class ViewClientDetailsControllerFactory implements FactoryInterface
{
//all Client info needed - full object graph
public function __invoke($container, $requestedName, $options)
{
$controller = new ViewClientDetailsController();
$loadDependencies = [
'loadPreferences' => true,
'loadOrders' => true,
'loadContacts' => true
];
$clientMapper = $container->get(ClientMapper::class, '', $loadDependencies);
return $controller;
}
}
class ViewAllClientsControllerFactory implements FactoryInterface
{
//Only need Client data - no related objects
public function __invoke($container, $requestedName, $options)
{
$controller = new ViewAllClientsController();
$loadDependencies = [
'loadPreferences' => false,
'loadOrders' => false,
'loadContacts' => false
];
$clientMapper = $container->get(ClientMapper::class, '', $loadDependencies);
return $controller;
}
}
The mapper factory passes the options to the tablegateway factory, that passes them on to the hydrator factory:
class ClientTableGatewayFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$hydrator = $container->get('HydratorManager')->get(ClientHydrator::class, '', $options);
$rowObjectPrototype = $container->get(Client::class);
$resultSet = new HydratingResultSet($hydrator, $rowObjectPrototype);
$tableGateway = new TableGateway('clients', $container->get(Adapter::class), null, $resultSet);
return $tableGateway;
}
Finally, we can define here how much info to load into the Client:
class ClientHydratorFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
//base ArraySerializable for Client object hydration
$arrayHydrator = new ArraySerializable();
$arrayHydrator->addStrategy('dateRegistered', new DateTimeStrategy());
$aggregateHydrator = new AggregateHydrator();
$aggregateHydrator->add($arrayHydrator);
if($options['loadAddress'] === true){
$aggregateHydrator->add($container->get('HydratorManager')->get(ClientsAddressHydrator::class));
}
if($options['loadOrders'] === true){
$aggregateHydrator->add($container->get('HydratorManager')->get(ClientsOrdersHydrator::class));
}
if($options['loadPreferences'] === true){
$aggregateHydrator->add($container->get('HydratorManager')->get(ClientsPreferencesHydrator::class));
}
if($options['loadContacts'] === true){
$aggregateHydrator->add($container->get('HydratorManager')->get(ClientsContactsHydrator::class));
}
return $aggregateHydrator;
}
}
This seems to be a clean solution, as the dependencies can be defined per request. However i don't think that this is using the options param as intended - the documentation states that this parameter is supposed to be for passing constructor params to the object, not defining what logic the factory should use to load dependencies.
Any advice, or alternative solutions to achieve the above, would be great. Thanks for reading.
Creating a big palette of all possible combinations would not be just a nightmare, but a declared suicide.
Using options
I wouldn't suggest you this option either. I mean, it's not that bad, but it has a major issue: everytime you instantiate your hydrator, you should remember to pass those options, or you'll get an "empty hydrator". Same logic applies to everything that uses those hydrators.
Since you actually want to remove hydrators you don't need, I'd suggest to avoid this solution, because this way you are always forced to declare which hydrators you need (and, honestly, I'll always forget to do it.. ^^ ).
If you add a new hydrator, you'll have to go through your project and add new options. Not really worth the effort...
That's why I propose you the next solution
Removing unnecessary hydrators
In 99% of the cases, hydrators are used by mappers. Thus, I think it would be cleanier to have a mapper which, by default, returns always the same kind of data (->a single hydrator), but that it can be modified to remove a certain set of hydrators.
Inside the AggregateHydrator, all hydrators are converted into listeners and attached to EventManager. I had some issue while trying to get all events, so I turned on creating an aggregate hydrator with the option to detach an hydrator:
class DetachableAggregateHydrator extends AggregateHydrator
{
/**
* List of all hydrators (as listeners)
*
* #var array
*/
private $listeners = [];
/**
* {#inherit}
*/
public function add(HydratorInterface $hydrator, int $priority = self::DEFAULT_PRIORITY): void
{
$listener = new HydratorListener($hydrator);
$listener->attach($this->getEventManager(), $priority);
$this->listeners[get_class($hydrator)] = $listener;
}
/**
* Remove a single hydrator and detach its listener
*
* #param string $hydratorClass
*/
public function detach($hydratorClass)
{
$listener = $this->listeners[$hydratorClass];
$listener->detach($this->getEventManager());
unset($listener);
unset($this->listeners[$hydratorClass]);
}
}
Then, in the TableGatewayFactory:
class ClientTableGatewayFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$hydrator = $container->get('HydratorManager')->get(ClientHydrator::class);
$rowObjectPrototype = $container->get(Client::class);
$resultSet = new HydratingResultSet($hydrator, $rowObjectPrototype);
$adapter = $container->get(Adapter::class);
$tableGateway = new TableGateway('clients', $adapter, null, $resultSet);
return $tableGateway;
}
}
And the ClientHydratorFactory:
class ClientHydratorFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$aggregateHydrator = new DetachableAggregateHydrator();
$arrayHydrator = new ArraySerializable();
$arrayHydrator->addStrategy('dateRegistered', new DateTimeStrategy());
$aggregateHydrator->add($arrayHydrator);
$hydratorManager = $container->get('HydratorManager');
$aggregateHydrator->add($hydratorManager->get(ClientsAddressHydrator::class));
$aggregateHydrator->add($hydratorManager->get(ClientsOrdersHydrator::class));
$aggregateHydrator->add($hydratorManager->get(ClientsPreferencesHydrator::class));
$aggregateHydrator->add($hydratorManager->get(ClientsContactsHydrator::class));
return $aggregateHydrator;
}
}
You just need to make tablegateway accessible by outstide the mapper:
class ClientMapper
{
private $tableGateway;
// ..
// Other methods
// ..
public function getTableGateway(): TableGateway
{
return $this->tableGateway;
}
}
And now you're able to choose which hydrators you don't want to attach.
Let's say you have two controllers:
ClientInfoController, where you need clients and their address, preferences and contacts
ClientOrdersController, where you need clients with their orders
Their factories will be:
class ClientInfoController implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$clientMapper = $container->get(ClientMapper::class);
// Orders are unnecessary
$resultSetPrototype = $clientMapper->getTableGateway()->getResultSetPrototype();
$resultSetPrototype->getHydrator()->detach(ClientsOrdersHydrator::class);
return $aggregateHydrator;
}
}
class ClientOrdersController implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$clientMapper = $container->get(ClientMapper::class);
// Orders are unnecessary
$resultSetPrototype = $clientMapper->getTableGateway()->getResultSetPrototype();
$resultSetPrototype->getHydrator()->detach(ClientsAddressHydrator::class);
$resultSetPrototype->getHydrator()->detach(ClientsPreferencesHydrator::class);
$resultSetPrototype->getHydrator()->detach(ClientsContactsHydrator::class);
return $aggregateHydrator;
}
}

ZF2: inject variables in constructor of service

Is there a way to create a new instance of a service and adding constructor parameters? I am a bit new to depency injection, and I find I can only add services as constructor parameters and not runtime variables through a factory.
The code I have looks similar to this:
Class MyService
{
private $name;
private $active;
public function __construct($name,$active)
{
$this->name = $name;
$this->active = $active;
}
}
$myService = $this->getServiceLocator()->get('MyService')
Yes there is a way by using the MutableCreationOptionsTrait trait in your factory.
class YourServiceFactory implements FactoryInterface, MutableCreationOptionsInterface
{
use MutableCreationOptionsTrait;
public function createService(ServiceLocatorInterface $serviceLocator)
{
if (isset($this->creationOptions['name'])) {
// do something with the name option
}
if (isset($this->creationOptions['active'])) {
// do something with the active option
}
$yourService = new YourService(
$this->creationOptions['active'],
$this->creationOptions['name']
);
return $yourService;
}
}
The above shown code implements the trait for creation options. With this trait you can handle an array of options in your factory. Call your service like in the following code.
$yourService = $this->getServiceLocator()->get(YourService::class, [
'active' => true,
'name' => 'Marcel',
]);
Easy as pie. ;)
Let's say your service exists:
Class MyService
{
private $name;
private $active;
public function __construct($name,$active)
{
$this->name = $name;
$this->active = $active;
}
}
If instead of ->get()'ing it, you could ->build() it :)
class SomeFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
return $container->build(MyService::class, ['name' => "Foo", 'active' => true]);
// Line below works as well, using a variable requested name, handy for an AbstractFactory of some kind (e.g. one that creates different adapters in the same way with same params)
// return $container->build($requestedName, ['name' => "Foo", 'active' => true]);
}
}
Check out the ServiceManager build() function
Note: Not sure since when it's present, this works in higher versions of ZF2 and all of ZF3.
Note 2: Both get() and build() call function doCreate(). Function declaration:
private function doCreate($resolvedName, array $options = null)
get() does: $object = $this->doCreate($name);
build() does: return $this->doCreate($name, $options);

How To Use toRoute in ZF2 View Helper

I want to use toRoute or redirect controller plugin in my view helper. I know View helpers extend functionality on the view layer and are for reusability throughout our application. Controller plugins extend functionality on the controller layer. But I want any other solution to do that.
Here is my view helper:
<?php
namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class GetSiteSettings extends AbstractHelper implements ServiceLocatorAwareInterface {
protected $serviceLocator;
/**
* Set the service locator.
*
* #param ServiceLocatorInterface $serviceLocator
* #return CustomHelper
*/
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
return $this;
}
/**
* Get the service locator.
*
* #return \Zend\ServiceManager\ServiceLocatorInterface
*/
public function getServiceLocator()
{
return $this->serviceLocator;
}
public function __invoke()
{
$redirect = $this->redirect()->toRoute('my_account');
/*$sm = $this->getServiceLocator()->getServiceLocator();
$config = $sm->get('Config');
return $config['site_settings'];*/
}
}
?>
In the above code, the line:
$redirect = $this->redirect()->toRoute('my_account');
is really not working and I also tried several things to achieve it, but nothing helped.
I've got it at my own. We can get the controller plugin manager service and then use any plugin.
$sm = $this->getServiceLocator()->getServiceLocator();
$redirect = $sm->get('ControllerPluginManager')->get('redirect');
$redirect->toRoute('my_account')

How to inject ServiceManager into a user defined class

In the doc it's said:"By default, the Zend Framework MVC registers an initializer that will inject the ServiceManager instance, which is an implementation of Zend\ServiceManager\ServiceLocatorInterface, into any class implementing Zend\ServiceManager\ServiceLocatorAwareInterface."
so I tried this:
interface ModelResourceInterface extends ServiceLocatorAwareInterface
{
}
interface ServiceModelResourceInterface extends ModelResourceInterface
{
public function fetch($uri, $method, $parameters, $options, $encodeType);
}
namespace Ssports\Model\Resource\Service\Http;
use Ssports\Model\Resource\Service\ServiceModelResourceInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Http\Client;
use Zend\Http\Request;
use Ssports\Model\Resource\Service\ConnectionException;
abstract class AbstractHttpServiceModelResource implements ServiceModelResourceInterface
{
/**
*
* #var Zend\ServiceManager\ServiceLocatorInterface;
*/
protected $serviceLocator;
/**
* Constructor
*/
function __construct()
{
$this->init();
}
/**
* Extend Constructor
*/
public function init()
{}
/**
* (non-PHPdoc)
*
* #see \Zend\ServiceManager\ServiceLocatorAwareInterface::setServiceLocator()
*
*/
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
/**
* (non-PHPdoc)
*
* #see \Ssports\Model\Resource\Service\ServiceModelResourceInterface::fetch()
*
*/
public function fetch($uri, $method, $parameters = null, $options = null, $encodeType = null)
{
try {
//something raise \RuntimeException
} catch (\RuntimeException $e) {
$this->getServiceLocator()->get('Log\Web');
throw new ConnectionException();
}
}
/**
* (non-PHPdoc)
*
* #see \Zend\ServiceManager\ServiceLocatorAwareInterface::getServiceLocator()
*
*/
public function getServiceLocator()
{
return $this->serviceLocator;
}
}
I extend this abstract class with some model resource class, and run it, and an exception throw to say that I'm calling get on a non-object.
Seem that the service manager is not being injected to my abstract class, and the return of getServiceLocator is NULL.
Any thing I missed to make it right?
Have you tried to use the service locator trait?
It can be found in \Zend\ServiceManager\ServiceLocatorAwareTrait
However this requires PHP 5.4 to work...
To use a trait do the following
class Class1
{
use Zend\ServiceManager\ServiceLocatorAwareTrait;
}
You can access the service locator then, or at least that is how i had to do it when i needed to load the service locator.

Resources