I am trying to create a simple service in zf2 which I can access using in viewhelper
Step1. I have craeted a class in src/Application/Service/Servic
change the line $this->sm->getServiceLocator()->get('Application\Service\Service1');
in below method
class Abc extends AbstractHelper
{
protected $sm;
public function test()
{
$this->sm->getServiceLocator()->get('Application\Service\Service1');
}
public function __construct($sm) {
$this->sm = $sm;
}
}
An alternative, in PHP 5.4 only, without specific configuration, would be to use traits:
extract of module.config.php:
'view_helpers' => array(
'invokables' => array(
'myHelper' => 'Application\View\Helper\MyHelper',
),
MyHelper.php:
<?php
namespace Application\View\Helper;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
class HeadScript extends \Zend\View\Helper\MyHelper implements ServiceLocatorAwareInterface
{
use \Zend\ServiceManager\ServiceLocatorAwareTrait;
public function __invoke()
{
$config = $this->getServiceLocator()->getServiceLocator()->get('Config');
// do something with retrived config
}
}