Zend \ ServiceManager \ ServiceManager :: get не удалось получить или создать экземпляр для getAlbumTable

Я пытаюсь изменить и скопировать настраиваемый модуль, я установил все соединения с БД, но получаю сообщение об ошибке при просмотре моего модуля следующим образом:

Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for getAlbumTable 

Вот мой файл module.config:

 return array( 'controllers' => array( 'invokables' => array( 'Album\Controller\Album' => 'Album\Controller\AlbumController', ), ), // The following section is new and should be added to your file 'router' => array( 'routes' => array( 'album' => array( 'type' => 'segment', 'options' => array( 'route' => '/album[/:action][/:id]', 'constraints' => array( 'action' => '[a-zA-Z][a-zA-Z0-9_-]*', 'id' => '[0-9]+', ), 'defaults' => array( 'controller' => 'Album\Controller\Album', 'action' => 'index', ), ), ), ), ), 'view_manager' => array( 'template_path_stack' => array( 'album' => __DIR__ . '/../view', ), ), ); 

И вот соединение с базой данных в global.php

 return array( 'db' => array( 'driver' => 'Pdo', 'dsn' => 'mysql:dbname=stickynotes;host=localhost', 'driver_options' => array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'' ), ), 'service_manager' => array( 'factories' => array( 'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory', ), ), ); 

Вот код из module.php для конфигурации служб:

  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); }, ), ); } 

Вот контроллер, чтобы получить альбом:

  <?php namespace Album\Controller; use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\ViewModel; class AlbumController extends AbstractActionController { protected $_albumTable; public function indexAction() { return new ViewModel(array( 'albums' => $this->getAlbumTable()->fetchAll(), )); } } ?> 

Вот вложение для таблиц базы данных: таблицы базы данных View

Может кто-нибудь, пожалуйста, сообщите мне, где я должен отладить эту ошибку и устранить проблему?

Related of "Zend \ ServiceManager \ ServiceManager :: get не удалось получить или создать экземпляр для getAlbumTable"

Когда вы вызываете $this->getAlbumTable() Zend ищет плагин контроллера, но нет никакого плагина с таким именем, поэтому он выдает исключение.

Если вы хотите получить доступ к любому классу из service_manager вам нужно ввести его через фабрику.

 use Interop\Container\ContainerInterface; use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; use MyNamespace\Controller\AlbumController; class AlbumControllerFactory implements FactoryInterface { /** * * @param ContainerInterface $container * @param string $requestedName * @param null|array $options * @return AlbumController */ public function __invoke(ContainerInterface $container, $requestedName, array $options = null) { $class = $requestedName ? $requestedName : AlbumController::class; $albumTable = $container->get('Album\Model\AlbumTable'); // get service from service manager $controller = new $class($albumTable); return $controller; } /** * Provided for backwards compatibility; proxies to __invoke(). * * @param ContainerInterface|ServiceLocatorInterface $container * @return AlbumController */ public function createService(ServiceLocatorInterface $container) { return $this($container, AlbumController::class); } } 

В module.config.php

 'controllers' => array( 'factories' => array( Controller\AlbumController::class => Factory\Controller\AlbumControllerFactory::class, ), ), 

В вашем контроллере:

  namespace Album\Controller; use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\ViewModel; class AlbumController extends AbstractActionController { protected $_albumTable; public function __construct(AlbumTable $albumTable) { $this->_albumTable = $albumTable; } public function indexAction() { return new ViewModel(array( 'albums' => $this->_albumTable->fetchAll() )); } } 

Простой, не так ли? 🙂

Я только что решил это, добавив Службы в моем модульном файле Module.php, теперь он работает нормально:

 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); }, ), ); }