0

在我的 Zend Framework 2 项目中,我有一个外部库,我想将我的信息与模型一起保存在基础中。

……………………

编辑信息:

我再次解释了我的需求:在我的控制器中,我在数据库中进行插入和删除,并且我想将所有操作记录在“t_log”表中。为此,我想创建一个外部类。

我的问题是:如何从外部类调用模型方法?

namespace Mynamespace;

use Firewall\Model\Logs;
use Firewall\Model\LogsTable;

class StockLog
{
    public function addLog()
    {
       $log = $this->getServiceLocator()->get('Firewall\Model\LogTable');
       $log->save('user added'); 
       die('OK');
    }
}

我的模型:

namespace Firewall\Model;

use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;

class UserGroupTable
{

    protected $tableGateway;

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    public function save()
    {
        // How I Can call this method from the StockLog method ?
    }
}

谢谢 !

4

1 回答 1

3

getServiceLocator是一个函数, \Zend\Mvc\Controller\AbstractActionController所以它应该在你的控制器中使用。

我不知道你的StockLog 类是什么,但它没有扩展任何其他类,所以我猜它没有那个功能,你的错误是前一步,在调用中getSErviceLocator没有定义,所以它没有返回一个对象。

可能你可以用类似的东西注入服务定位器

class StockLog 
{

  private $serviceLocator= null;

  public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
  {
    $this->serviceLocator = $serviceLocator;
  }


    public function add()
    {
       # Do you know how I can call the service ??
       $User = $this->serviceLocator->get('Firewall\Model\UserTable');
    }


}

然后,当您创建 StockLog 对象时,在您的控制器中,您注入服务定位器

public class yourController extends AbstractActionController {

   public function yourAction(){
      $mStockLog = new StockLog ();
       $mStockLog->setServiceLocator($this->getServiceLocator()); 
    /...

   }
}

此外,如果您只需要该 'Firewall\Model\UserTable'服务,则应该只注入该服务,而不是 serviceLocator。

无论如何,您应该尽量减少模型类对系统其余部分的了解,始终牢记依赖倒置原则,以获得更好的解耦

更新

注入日志表

namespace Mynamespace;

use Firewall\Model\Logs; use Firewall\Model\LogsTable;

class StockLog {


 private $logTable= null;

  public function setLogTable($logTable)
  {
    $this->logTable= $logTable;
  }

public function addLog()
{

   $this->logTable->save('user added'); 
   die('OK');
}

}

然后,当您创建 StockLog 时(在您的控制器中,或在您使用它的任何地方)您注入 logtable 对象

  $mStockLog = new StockLog ();
  $mStockLog->setLogTable($this->getServiceLocator()->get('Firewall\Model\LogTable')); 

当然,我假设您正确配置Firewall\Model\LogTable了要通过服务管理器检索的类, getServiceConfig()在您的Module.php

  public function getServiceConfig() {
       return array (
            'factories' => array (
                    'Firewall\Model\LogTable' => function ($sm) {
                         $logTable = //create it as you use to  
                  return $logTable;
            }  

        )

  }
于 2014-01-02T15:49:53.717 回答