John John - 2 months ago 9
PHP Question

Construct() must be an instance

I'm following the ZF2 Manual and I'm facing this error:

"Catchable fatal error: Argument 1 passed to Album\Model\AlbumTable::__construct() must be an instance of Zend\Db\TableGateway\TableGateway, instance of Zend\Db\Adapter\Adapter given, called in /var/www/CommunicationApp/module/Album/Module.php on line 33 and defined in /var/www/CommunicationApp/module/Album/src/Album/Model/AlbumTable.php on line 11"

I don't know what I'm missing, because it's exactly the same as the tutorial.

<?php

namespace Album\Model;

use Zend\Db\TableGateway\TableGateway;

class AlbumTable
{
protected $tableGateway;

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

public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}

public function getAlbum($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}

public function saveAlbum(Album $album)
{
$data = array(
'artist' => $album->artist,
'title' => $album->title,
);

$id = (int) $album->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getAlbum($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Album id does not exist');
}
}
}

public function deleteAlbum($id)
{
$this->tableGateway->delete(array('id' => (int) $id));
}
}


Module.php:

<?php
namespace Album;
use Album\Model\AlbumTable;


class Module
{
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}

public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}

public function getServiceConfig()
{
return array(
'factories' => array(
'Album\Model\AlbumTable' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new AlbumTable($dbAdapter);
return $table;
},
),
);
}
}

Answer

You should pass TableGetway to AlbumTable. change Module.php and replace getServiceConfig with:

 public function getServiceConfig()
 {
     return array(
         'factories' => array(
             'Album\Model\AlbumTable' =>  function($sm) {
                 $tableGateway = $sm->get('AlbumTableGateway');
                 $table = new AlbumTable($tableGateway);
                 return $table;
             },
             'AlbumTableGateway' => function ($sm) {
                 $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                 $resultSetPrototype = new ResultSet();
                 $resultSetPrototype->setArrayObjectPrototype(new Album());
                 return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
             },
         ),
     );
 }