【问题标题】:ZF2: Accessing method from different class from within a classZF2:从一个类中访问不同类的方法
【发布时间】:2013-06-12 18:56:00
【问题描述】:

在“事件”类中,我想将“客户”类中的“客户名称”变量分配给“类”变量之一。我的类CustomerTable 有一个名为“getCustomer”的方法,它通过传递一个customerId 创建一个Customer 实例。我想从我的 Event 类中调用该方法,以便我可以从该客户那里获取客户名称并将其分配给 Event。

我已经尝试让 Event 扩展 AbstractActionController 并使用服务管理器来获取方法,如下面的示例所示。但是当我尝试在 CustomerTable 类上调用 get() 时,会触发一条消息,指出我正在尝试在非对象上调用 get()。

基本上:有人知道我如何在 Event 类中调用 getCustomer() 吗?

我认为的我的事件类:

class Event
{
    public $id;
    public $CCID;
    public $customerName;   
    public $jobId;
    public $timeServer;
    public $timeConvert;
    public $messageId;
    public $message = null;
    public $severity;
    public $client;

    public function exchangeArray($data)
    {
        $this->id       = (isset($data['id'])) ? $data['id'] : null;
        $this->CCID     = (isset($data['CCID'])) ? $data['CCID'] : null;
        // here's the stuff that tries to get the getCustomer() method
        $sm                 = $this->getServiceLocator();
        $customer            = $sm->get('Admin\Model\CustomerTable')->getCustomer($this->CCID);
        $this->customerName = $customer->customerName;
        $this->jobId    = (isset($data['jobId'])) ? $data['jobId'] : null;
        $this->timeServer   = (isset($data['TimeServer'])) ? $data['TimeServer'] : null;
        $this->messageId    = (isset($data['messageId'])) ? $data['messageId'] : null;
        $this->severity     = (isset($data['Severity'])) ? $data['Severity'] : null;
        $this->client       = (isset($data['Client'])) ? $data['Client'] : null;
        $this->timeConvert  = gmdate("H:i", $this->timeServer);
    }
}

【问题讨论】:

  • 您是否尝试在 Event 扩展 AbstractActionController 时包含 AbstractActionController 文件?也许因为那个原因它没有工作?
  • 有没有想过将你需要的类注入到你的模型中?此外,不要注入ServiceLocator只注入CustomerTable

标签: php zend-framework2


【解决方案1】:

这里有两个加载类的例子:

use \Admin\Model\CustomerTable; // use namespaces
$sm = new CustomerTable();
$customer = $sm->getCustomer($this->CCID);

或者这样做

$sm = new \Admin\Model\CustomerTable\Tidy();
$customer = $sm->getCustomer($this->CCID);

【讨论】:

    猜你喜欢
    • 2022-12-05
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 2019-03-10
    • 1970-01-01
    • 2015-01-21
    相关资源
    最近更新 更多