Search code examples
phpzend-dbzend-framework2

Where condition in ZF2 using Anonymous function


As the official documentation say I'm using an anonymous PHP function in my ZF2 model (Zend\Db\TableGateway)

 use Zend\Db\TableGateway\TableGateway;
 use Zend\Db\Sql\Select;
 $artistTable = new TableGateway('artist', $adapter);

 // search for at most 2 artists who's name starts with Brit, ascending
 $rowset = $artistTable->select(function (Select $select) {
      $select->order('name ASC');
 });

How to pass an argument in this anonymous function to add a filter in the where condition?

I would like to use something like that:

$this->select(function (Select $select) {
            $select->where(array('artist', $artist));
            $select->order('name ASC');
});

Thanks!


Solution

  • Try this

    $artist = 'John';
    $rowset = $artistTable->select(function (Select $select) use ($artist) {
        $select->where(array('artist', $artist));
        $select->order('name ASC');
    });