Based on reply from ZF2: Attach event to another Controller's Action and get Service Locator, I am attaching an event to a controller's action like this
$loader = $sl->get('ControllerLoader');
$loginController = $loader->get('B\Controller\LoginController');
$sharedEventManager->attach('A\Controller\LoginController',
'checkme.post',
array($loginController, 'loginAction'),
100);
When event fire, It goes inside loginAction of "B"'s controller. Inside loginAction when I try to call other method of B\LoginController, then I get an error of
Fatal error: Using $this when not in object context in C:\wampp\www\Zend2\module\B\src\B\Controller\LoginController.php Blockquote on line 60
CONTROLLER CODE:
<?php
namespace B\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Soap\Client;
class LoginController extends AbstractActionController {
public function loginAction($e) {
$user_id = $e->getParam('user_id');
$config = $e->getParam('config');
if($user_id){
$client = $this->getSoapClient($config);
$params = $this->enrolmentRequestParams($user_id);
$response = $client->getEnrolment($params);
$course_enrolment = $response->enrolment_list->value->course_enrolment_list->course_enrolment;
$this->processEnrolmentData($course_enrolment);
}
}
public function getSoapClient($config){
$options = array(
'soap_version'=> $config['webservice_config']['soap_version'],
'location' => $config['webservice_config']['location']
);
$wsdl = $config['webservice_config']['wsdl'];
$client = new \Zend\Soap\Client($wsdl, $options);
return $client;
}
public function processEnrolmentData($course_enrolment){
foreach($course_enrolment as $ce){
// some code here
}
}
public function enrolmentLookUp($e){
//some code here
}
public function enrolmentRequestParams($sid){
//some code here
}
public function emptyObject($theObject){
$tmp = (array) $theObject;
if(empty($tmp)) {
return true;
}else{
return false;
}
}
public function validVal($uos){
if(!empty($uos) && !is_null($uos) && isset($uos)){
return true;
}else{
return false;
}
}
public function getSemesterNo($value){
return preg_replace("/[^0-9]/","",$value);
}
}
?>
Please help in this regard.
If you pass an array as the callback, the class method is called statically (i.e. equivalent to you doing
LoginController::loginAction(e)
). There is no$this
, because the function is not being called on an instance of the class.It looks like most of the logic you have in the controller class shouldn't be in a controller at all. I'd suggest moving it to a separate class which you can then adjust to better handle static method calls.