ZF2保存到多个表

时间:2016-03-05 07:08:09

标签: php model-view-controller zend-framework

我有一个映射器类OrganizationMapper,它使用save方法将数据保存到多个表中。 save方法如下所示:

public function save(OrganizationInterface $organization) {
        $action = new Insert('TABLE NAME');
        $action->values([<SOME VALUES>]);
        $sql = new Sql($this->dbAdapter);
        $stmt = $sql->prepareStatementForSqlObject($action);
        $result = $stmt->execute();

        $action1 = new Insert('OTHER TABLE NAME');
        $action1->values([OTHER VALUES]);
        $sql1 = new Sql($this->dbAdapter);
        $stmt1   = $sql1->prepareStatementForSqlObject($action1);
        $result1 = $stmt1->execute();
        ...
}

还有几个周期$action#$sql#$stmt#$result#

如何避免这些重复循环?

1 个答案:

答案 0 :(得分:1)

为避免重复代码创建其他方法,我们将其称为insertIntoTable()。此方法将是将数据插入某个表的辅助函数:

public function save(OrganizationInterface $organization) {
        $result = $this->insertIntoTable('TABLE NAME', $values);

        $result1 = $this->insertIntoTable('OTHER TABLE NAME', $values1);
        ...
}

private function insertIntoTable($tableName = "", $values) {
        $action = new Insert($tableName);
        $action->values($values);
        $sql = new Sql($this->dbAdapter);
        $stmt = $sql->prepareStatementForSqlObject($action);
        $result = $stmt->execute();

        return $result;
}