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;
}
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.
Related
It looks like it has been touched several times already, but i still can't get it work. I set up an JSON-RPC server in a separate module, it works fine. Its functionality is in a new class Rpcapi. Now I want reuse DB related functions that already implemented in another module from that class. According to ZF2 docs my Rpcapi class has to be ServiceLocator-aware and it looks like I made it that way. Unfortunatelly still can't get it working. Please help keeping in mind that I'm new with ZF2 :)
Rpccontroller.php
namespace Rpc\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Json\Server\Server;
use Zend\Json\Server\Smd;
use Rpc\Model\Rpcapi;
class RpcController extends AbstractActionController
{
public function indexAction()
{
header('Content-Type: application/json');
$jsonrpc = new Server();
$jsonrpc->setClass(new Rpcapi);
$jsonrpc->getRequest()->setVersion(Server::VERSION_2);
if ($this->getRequest()->getMethod() == "GET") {
$smd = $jsonrpc->getServiceMap()->setEnvelope(Smd::ENV_JSONRPC_2);
echo $smd;
} else {
$jsonrpc->handle();
}
}
}
module.config.php for Rpc module
'service_manager' => array(
'invokables' => array(
'rpcapi' => 'Search\Model\SiteTable',
),
),
Rpcapi.php
namespace Rpc\Model;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class Rpcapi implements ServiceLocatorAwareInterface
{
protected $services;
protected $siteTable;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->services = $serviceLocator;
}
public function getServiceLocator()
{
return $this->services;
}
public function getSiteTable()
{
if (!$this->siteTable) {
$sm = $this->getServiceLocator();
$this->siteTable = $sm->get('rpcapi');
}
return $this->siteTable;
}
/**
* Returns list of all sites
*
*
* #return array
*/
public function getAllSites()
{
$results = $this->getSiteTable()->fetchAll();
$r = array ('1' => '1', '2' => 2); //Just to return something for now
return $r;
}
}
All I could get out is: Fatal error: Call to a member function get() on a non-object in /var/www/html/AmeriFluxZF2/module/Rpc/src/Rpc/Model/Rpcapi.php on line 28. Line 28 is:
$this->siteTable = $sm->get('rpcapi');
Any help is much appreciated!
Making the class service locator aware tells the ZF2 that the service locator should be injected into your class upon instantiation. However, you still need to use the service locator to instantiate this class, rather than creating an instance of it yourself, or this will never happen.
Your probably want to add a new entry to invokables for your Rpcapi class, and then grab this from the service locator instead of doing new Rpcapi in your controller.
PS: The naming of your classes is very confusing - you have an Rpcapi class, and an invokable called rpcapi, yet this invokable creates an instance of a completely different class?
If you want serviceLocator to be injected by the service manager in your Rpcapi, you must get it via the service manager itself :
'service_manager' => array(
'invokables' => array(
'rpcapi' => 'Search\Model\SiteTable',
'Rpc\Model\Rpcapi' => 'Rpc\Model\Rpcapi',
),
),
the action :
public function indexAction()
{
header('Content-Type: application/json');
$jsonrpc = new Server();
$jsonrpc->setClass($this->getServiceLocator()->get('Rpc\Model\Rpcapi'));
$jsonrpc->getRequest()->setVersion(Server::VERSION_2);
if ($this->getRequest()->getMethod() == "GET") {
$smd = $jsonrpc->getServiceMap()->setEnvelope(Smd::ENV_JSONRPC_2);
echo $smd;
} else {
$jsonrpc->handle();
}
}
And this is where you can see that your 'rcpai' name for SiteTable is not a good choice... ;)
I have this code, where to get getEventManager but does not seem to work:
<?php
namespace Application\Service;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;
class ServiceUser implements EventManagerAwareInterface
{
protected $eventManager;
public function insert($data)
{
$this->getEventManager()->trigger('user.new', $this, array('user' => $data));
}
public function setEventManager(EventManagerInterface $eventManager)
{
$eventManager->addIdentifiers(array(__CLASS__, get_called_class(), 'Module\User'));
$this->eventManager = $eventManager;
return $this;
}
public function getEventManager()
{
return $this->eventManager;
}
}
the error that is generated:
Call to a member function trigger() on a non-object in
How do you construct your ServiceUser object? The *Aware interfaces only work when you construct them via the service locator.
So, you need to register the service in your configuration:
'service_manager' => array(
'invokables' => array(
'user-service' => 'My\Foo\Service\User',
),
),
And then request the service via the service locator (for example, in your controller):
$service = $this->getServiceLocator()->get('user-service');
This will give you a service where the event manager is injected into.
guys,
At this point i am close to start pulling hair out of my head. I don't find a way to achieve this.
I have a custom class that belongs to a custom folder i created under my WebServices Module src folder. I need to be able to instantiate this class from inside another module/controller but when i do that and dump the services member it contains null.
How can i have the service manager accesible from inside my ApiAuthentication class.
Any help will be appreciated. Thanks
<?php
namespace WebServices\Services;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class ApiAuthenticationService extends \Zend\Soap\Client implements ServiceLocatorAwareInterface{
public $services;
function __construct($options = null){
parent::__construct('http://tinysoa.local/soap/security/api_authentication?wsdl',$options);
}
public function setServiceLocator(ServiceLocatorInterface $locator)
{
$this->services = $locator;
}
public function getServiceLocator()
{
return $this->services;
}
}
When i call this from inside another module/controller it dumps a null value:
class IndexController extends AbstractActionController
{
public function indexAction()
{
$a = new \WebServices\Services\ApiAuthenticationService();
var_dump($a->services);
Responding with my own answer to add-on to Adrian's, and the question you asked in response.
If your service has dependencies of it's own, you just use a factory instead of going the invokable route.
Say your service needs a cache adapter and database adapter. Also imagine that it can optionally be configured with some other service (FooService, below):
<?php
public function getServiceConfig()
{
return array(
'factories' => array(
'my_service' => function($sm){
$cache = $sm->get('Cache');
$dbAdapter = $sm->get('DefaultDbAdapter');
$fooService = $sm->get('FooService');
// instantiate your service with required dependencies
$mySvc = new \My\Shiny\Service($cache, $dbAdapter);
// inject an optional dependency
$mySvc->setFooService($fooService);
// return your shiny new service
return $mySvc;
}
)
);
}
Side Note: It's generally bad design to inject the ServiceManager all over the place. You're better off managing your dependencies more explicitly, like above.
This stuff is covered quite well in the Quick Start, if you haven't already read that.
Register your Service in Service Config and access it through getServiceLocator() method in controller.
Module.php
public function getServiceConfig()
{
return array(
'invokables' => array(
'my_service' => 'WebServices\Services\ApiAuthenticationService'
)
);
}
Controller
public function indexAction()
{
$service = $this->getServiceLocator()->get('my_service');
}
I currently have a ZF2 Module which needs access to three database tables. No other module needs access to these tables.
So my question is (performance in mind too, please) should I really add the factories to the Module.php like I have been doing:
/**
* Service Configuration
*
* #return array
*/
public function getServiceConfig()
{
return array(
'invokables' => array(
'Login\Service\Authenticate' => 'Login\Service\Authenticate',
'Login\Service\Oauth' => 'Login\Service\Oauth'
),
'factories' => array(
'Login\Form\Login' => function () {
$form = new Form\Login();
$form->setInputFilter(new FormFilter\Login());
return $form;
},
'Login\Model\GaclEmployeePermission' => function ($sm) {
return new Model\GaclEmployeePermission($sm->get('OTWebsoft\Db\Adapter\Master'), $sm->get('OTWebsoft\Db\Adapter\Slave'));
},
'Login\Model\Passport' => function ($sm) {
return new Model\Passport($sm->get('OTWebsoft\Db\Adapter\Master'), $sm->get('OTWebsoft\Db\Adapter\Slave'));
},
'Login\Model\PassportLog' => function ($sm) {
return new Model\PassportLog($sm->get('OTWebsoft\Db\Adapter\Master'), $sm->get('OTWebsoft\Db\Adapter\Slave'));
}
)
);
}
Then I have an abstract class which does:
/**
* Table GaclEmployeePermission
*
* #return \Login\Model\GaclEmployeePermission
*/
protected function getTableGaclEmployeePermission()
{
return $this->getServiceManager()->get('Login\Model\GaclEmployeePermission');
}
OR should I just remove the configuration from the Module.php and in my abstract class just do this:
/**
* Table GaclEmployeePermission
*
* #return \Login\Model\GaclEmployeePermission
*/
protected function getTableGaclEmployeePermission()
{
return new GaclEmployeePermission($this->getMasterAdapter(), $this->getSlaveAdapter());
}
Both seems to work exactly the same. But when it comes to performance, which would you recommend? Keeping in mind, these three tables do not need to be accessed from any other module but this one.
The main reason to use a service manager or dependency injection container is not that other services could access it. The main reason is to apply dependency injection and thereby you apply inversion of control. This ease the usage of your objects, allow you to swap implementations easily, enhance the ability to test the class and to keep the class responsible about the contained logic and not bothering its dependencies.
In both examples, you actually use the service manager but it's still the same pattern: the class (inside getTableGaclEmployeePermission()) decides what to get. Either via the service manager or via direct instantiation, that does not actually matter much.
By your module configuration I cannot grasp the layers you have in the application and what they do (esp. what's about that abstract class), but in general, you should inject it's dependencies:
abstract class SomeAbstract
{
protected $permission;
public function __construct(Permission $permission)
{
$this->permission = $permission;
}
}
class Permission
{
protected $master;
protected $slave;
public function __construct(TableAdapter $master, TableAdapter $slave = null)
{
$this->master = $master;
if (null !== $slave) {
$this->slave = $slave;
}
}
}
Then you create the service manager configuration to inject those dependencies for the services you define:
'factories' => array(
'Login\Model\Permission' => function ($sl) {
$master = $sl->get('My\MasterAdapter');
$slave = null;
if ($some_flag) {
$slave = $sl->get('My\SlaveAdapter');
}
return new Login\Model\Permission($master, $slave);
},
'Login\Some\ConcreteImplementation' => function ($sl) {
$permission = $sl->get('Login\Model\Permission');
return new Login\Some\ConcreteImplementation($permission);
}
),
Then you request Login\Some\ConcreteImplementation and all the injection ($master, $slave and $permission) is done for you, enabling all the benefits described above.
I'm quite new to zf2 and I'm experimenting with it. I have a view helper and I need it to access a table object. In my controller I can run:
$this->getServiceLocator();
But ideally I would run this inside my view helper. Unfortunately, I can't seem to access it from within my view helper. I tried passing it through the constructor, configuring a factory method in module.config.php, but when I try that, Zend will no longer pass a tablegateway object into one of my model objects created from a service factory method in the module's Module.php file. This seems to be because it no longer calls the factory method, and opts to run instantiate without any parameters.
I'm not certain I understand why the view factory methods would affect a different set of factory methods with different names.
Can anyone tell me what is wrong with what I'm doing? I can provide more details, but at this point I'm unclear on what details are actually important without supplying the entire codebase.
Thanks.
Crisp does provide a valid answer to your question, but I would suggest to take it one step further. The injection of the service locator makes your view helper tightly coupled to the framework and service locator pattern and vulnerable because every piece of code inside your application can modify every service in the service locator.
There are reasons to inject your dependency directly, so you only depend on your dependencies and you're not implementing this anti-pattern anymore. Let's assume your view helper depends on MyModule\Model\MyTable, then the constructor of your view helper would just look like this:
namespace MyModule;
use MyModule\Model\MyTable;
use Zend\View\Helper\AbstractHelper;
class MyViewHelper extends AbstractHelper
{
protected $table;
public function __construct(MyTable $table)
{
$this->table = $table;
}
}
As you pointed out, you just inject your MyTable now:
namespace MyModule;
class Module
{
public function getViewHelperConfig()
{
return array(
'factories' => array(
'MyViewHelper' => function($sm) {
$sm = $sm->getServiceLocator(); // $sm was the view helper's locator
$table = $sm->get('MyModule_MyTable');
$helper = new MyModule\View\Helper\MyHelper($table);
return $helper;
}
)
);
}
}
Note that inside a view helper factory your service manager is the view helper's service manager and not the "main" one where the table is registered (see also a blog post of I wrote earlier). The $sm->getServiceLocator() solves this for you.
I'm not certain I understand why the view factory methods would affect a different set of factory methods with different names.
It's not, so there is probably a bug in your code. If above does not work, please provide some more details on your service manager configuration so I can update my answer.
One of the great advantages of above approach is you make unit testing really easy for your view helper. You can mock the table gateway and focus on the complete behaviour of your view helper.
use MyModule\View\Helper\MyHelper;
public function testHelperusesTable
{
$mock = $this->getMock('MyModule\Model\MyTable');
$helper = new MyHelper($mock);
// Test your $helper now
}
You can inject the service locator into your view helper from the view helper config in Module.php
// Application/Module.php
public function getViewHelperConfig()
{
return array(
'factories' => array(
'myViewHelper' => function ($serviceManager) {
// Get the service locator
$serviceLocator = $serviceManager->getServiceLocator();
// pass it to your helper
return new \Application\View\Helper\MyViewHelper($serviceLocator);
}
)
);
}
In your view helper
<?php
namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper,
Zend\ServiceManager\ServiceLocatorInterface as ServiceLocator;
class MyViewHelper extends AbstractHelper
{
protected $serviceLocator;
public function __construct(ServiceLocator $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
}
While working in Zend Framework,we often need custom helper,that make our work easy, In zf1 accessing database model from helper was easy,but i got stuck that how to access database model for any table in Custom View Helper, but as i was needing it i get around through the problem in unprofessional way by creatina new db adapter object in the view, which was never good way, but recently i came to know through very interesting way to access the database adapter in the view helper and there i have to execute any query on any table, it may be not so Zend F2 way, but very simple and short way to solve the issue.
Here is my Model Example...
<?php
namespace Application\Model;
use Zend\Db\TableGateway\TableGateway;
class SlideImageSubTable {
protected $tableGateway;
public $adapter;
public function __construct(TableGateway $tableGateway) {
$this->tableGateway = $tableGateway;
$this->adapter = $this->tableGateway->getAdapter();
}
public function fetchAll() {
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function getSlideImageSub($id) {
$id = (int) $id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
public function getImageMenu($id) {
$id = (int) $id;
$rowset = $this->tableGateway->select(array('slide_image_id' => $id));
$rows = array_values(iterator_to_array($rowset));
if (!$rows) {
throw new \Exception("Could not find row $id");
}
return $rows;
}
public function saveSlideImageSub(SlideImageSub $slideImageSub) {
$data = array(
'slide_image_id' => $slideImageSub->slide_image_id,
'title' => $slideImageSub->title,
'description' => $slideImageSub->description
);
$id = (int) $slideImageSub->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getSlideImageSub($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Form id does not exist');
}
}
}
public function deleteSlideImageSub($id) {
$this->tableGateway->delete(array('id' => $id));
}
}
Just look at the 'public $adapter' public variable. And in the constructor i am going to initialize it by calling $this->tableGateway->getAdapter(); method, getAdapter() is available thorugh gateway object.
Then in my controller action view, i have to assign it to any variable and pass that variable to view page. like this..
public function equitiesAction() {
$image_id = $this->params('id');
$result = $this->getTable('SlideImageSub')->getImageMenu($image_id);
$adapter = $this->table->adapter;
$view = new ViewModel(array(
'result' => $result,
'adapter' => $adapter,
));
return $view;
}
And in the view i pass the 'adapter' object to custom view like this..
<?php echo $this->GetMenuProducts( $this->adapter); ?>
Now in custom view i can use this database adapter object and create select query on any table.
Hope this will help someone, i look around for using database access in custom view helper but the configurations methods provided was not working for me.
Thanks
$this->getView()->getHelperPluginManager()->getServiceLocator();