ZF2:当不在对象上下文中时使用$ this访问控制器内的其他方法时

时间:2013-10-31 12:03:23

标签: events controller zend-framework2

根据ZF2: Attach event to another Controller's Action and get Service Locator的回复,我将事件附加到控制器的行为中

$loader = $sl->get('ControllerLoader');
$loginController = $loader->get('B\Controller\LoginController');

$sharedEventManager->attach('A\Controller\LoginController',
                            'checkme.post',
                            array($loginController, 'loginAction'),
                            100); 

当事件触发时,它进入“B”控制器的loginAction内部。在loginAction里面,当我尝试调用B \ LoginController的其他方法时,我得到了

的错误
  

致命错误:在不在对象上下文中时使用$ this   C:\ wampp \ WWW \ Zend2 \模块\ B \ SRC \ B \控制器\ LoginController.php   大段引用   在第60行

控制器代码:

<?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);
    }

}

?>

请帮助这方面。

1 个答案:

答案 0 :(得分:1)

如果将数组作为回调传递,则会静态调用类方法(即等同于您执行LoginController::loginAction(e))。没有$this,因为没有在类的实例上调用该函数。

看起来你在控制器类中拥有的大多数逻辑都不应该在控制器中。我建议将它移动到一个单独的类,然后你可以调整它以更好地处理静态方法调用。