Steve McAlister
Steve McAlister

Reputation: 51

How to set Array Object Prototype for a Result Set of an Sql statement created with Sql object‏ in ZF2

I want to use the Sql object in my model to query the database. I have an entity object lets say Person and person object has exchangeArray() method. I want to set this Person object to be an Array Object Prototype of the ResultSet for my sql queries.

I research how to do this but the only information I found is how to set Array Object Prototype to a ResultSet object assigned to a Zend\Db\TableGateway\TableGateway.

$personEntity = new PersonEntity();
$resultSet = new \Zend\Db\ResultSet\ResultSet();
$resultSet->setArrayObjectPrototype($personEntity);
$db = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Zend\Db\TableGateway\TableGateway('table', $db, null, $resultSet);

My question is how can I set PersonEntity object to represent rows of my database that are return from a Zend\Db\Sql\Sql objects?

Thanks in advance,

Steve

Upvotes: 2

Views: 5978

Answers (2)

Stoyan Dimov
Stoyan Dimov

Reputation: 5539

I think the following example will answer your question:

class Foo
{
    ...
    public function fetchAll() 
    {
        $sql = new Sql($dbAdapter); // Zend\Db\Sql\Sql
        $select = $sql->select('table_foo');
        $query = $sql->prepareStatementForSqlObject($select);
        $resutl = $query->execute();
        $resultSet = new ResultSet(); // Zend\Db\ResultSet\ResultSet
        $resultSet->setArrayObjectPrototype(new EntityObject()); // <-- HERE you set your entity object
        $resultSet->initialize($resutl);
        return $resultSet;
    }
    ...
}

This code will return a ResultSet object in which every row return will be repsresented by, in this case, EntityObject.

Here is a reference to the manual that shows injection of the dataSource into a result object.

Upvotes: 4

Dim Dov
Dim Dov

Reputation: 73

You can set an array object prototype to any result set that you want like this:

$resultSet->setArrayObjectPrototype(new Entity);

Upvotes: 3

Related Questions