Fatal error: Class 'Album\Album' not found in /var/www/html/zf2/module/Album/Module.php on line 43
this error is showing whenever i am trying ti access localhost/album
my module.php
<?php
namespace Album;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Album\Model\AlbumTable;
class Module implements AutoloaderProviderInterface,ConfigProviderInterface{
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) {
$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);
},
),
);
}}?>
how to solve this error?
please give me the solution,zend is looking so tough i m trying to learn zend from 2 weeks bt this error is just eating my mind.
please help guyz
Make sure your namespaces are set up correctly. Your Album class has to be in the Album namespace if you're calling it like you are. Otherwise use the fully qualified name.
I'm new to ZF2 and are trying to create a custom view helper. In a view called profiles.phtml I do
echo $this->MyModuleHelper()->greetings('stack');
Which is resulting in
Fatal error: Class 'Dashboard\View\Helper\MyModuleHelper' not found in C:\dashboard\Application\module\Dashboard\Module.php on line 112
What am I missing and/or doing wrong?
Application/module/Dashboard/Module.php
namespace Dashboard;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\ModuleManager\Feature\ViewHelperProviderInterface;
use Dashboard\View\Helper\MyModuleHelper;
class Module implements ViewHelperProviderInterface {
public function onBootstrap(MvcEvent $e) {
//Some stuff
}
public function getConfig() {
return include __DIR__ . '/config/module.config.php';
}
public function getAutoloaderConfig() {
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getViewHelperConfig() {
return array(
'factories' => array(
'MyModuleHelper' => function ( $sl ) {
return new MyModuleHelper(); //Line 112
}
),
);
}
}
Application/module/Dashboard/view/Helper/MyModuleHelper.php
namespace Dashboard\View\Helper;
use Zend\View\Helper\AbstractHelper;
class MyModuleHelper extends AbstractHelper {
public function __invoke() {
return $this;
}
public function greetings( $userName ) {
return $this->escapeHtml( sprintf("Hello, %s! ", $userName) );
}
}
Side note: I've also tried registering it in module.config.php (instead of Module.php) like
'view_helpers' => array(
'invokables' => array(
'MyModuleHelper' => 'Dashboard\View\Helper\MyModuleHelper',
)
)
As mentioned in the comments I had the directory structure messed up.
I placed my helper in
Application/module/Dashboard/view/Helper/MyModuleHelper.php
When it should have been put in
Application/module/Dashboard/src/Dashboard/View/Helper/MyModuleHelper.php
I'm new to using ZF2, and running into an issue getting the first project I need to work on set up locally. I've gone through and set up the application locally, but when I try to access the home page I receive the following exception error:
Fatal error: Uncaught exception
'Zend\ModuleManager\Exception\RuntimeException' with message 'Module
(Application) could not be initialized.' in
/var/www/myproject/vendor/ZF2/library/Zend/ModuleManager/ModuleManager.php
on line 140
Zend\ModuleManager\Exception\RuntimeException: Module (Application)
could not be initialized. in
/var/www/myproject/vendor/ZF2/library/Zend/ModuleManager/ModuleManager.php
on line 140
There is also some output being echoed from a Call Stack trace.. not sure if it will be helpful in resolving this:
getApplication()->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); $this->initDatabase($e); } public function initDatabase($e) { Feature\GlobalAdapterFeature::setStaticAdapter($e->getApplication()->getServiceManager()->get('Zend\Db\Adapter\Adapter')); } public function getConfig() { return include __DIR__ . '/config/module.config.php'; } public function getServiceConfig() { return array( 'factories' => array( 'dbadapter' => new Zfe\Factory('db'), ), ); } public function getAutoloaderConfig() { return array( 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, ), ), ); } }
An image with the full stack trace and errors:
There was a very similar question already posted about this topic: Zend Framework 2 tutorial: Module (Application) could not be initialized .
Reading through that posting I followed the suggested answers recommendations of setting an absolute path for module_paths within application.config.php, however this did not affect my problem.
application.config.php excerpt:
'module_paths' => array(
__DIR__.'/../module',
'./vendor',
),
<?
namespace Application;
use Zend\Db\TableGateway\Feature;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\ModuleManager\Feature\ServiceProviderInterface;
use Model;
use Zfe;
class Module implements ServiceProviderInterface {
public function onBootstrap(MvcEvent $e) {
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$this->initDatabase($e);
}
public function initDatabase($e) {
Feature\GlobalAdapterFeature::setStaticAdapter($e->getApplication()->getServiceManager()->get('Zend\Db\Adapter\Adapter'));
}
public function getConfig() {
return include __DIR__ . '/config/module.config.php';
}
public function getServiceConfig() {
return array(
'factories' => array(
'dbadapter' => new Zfe\Factory('db'),
),
);
}
public function getAutoloaderConfig() {
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
}
Any insight as to where I could look to start debugging this would be much appreciated!
As per my comment, the error indicates ZF couldn't find the module class. In this case it is because a short open tag is being used (<? instead of <?php). PHP code being output is generally a good indicator of this.
In Zend Framework 2 it's quite easy to use a custom class instead of an invocable one from the framework. E.g. a ViewHelper:
namespace Application;
...
class Module {
public function onBootstrap(MvcEvent $mvcEvent) {
$application = $mvcEvent->getApplication();
$serviceManager = $application->getServiceManager();
$viewHelperManager = $serviceManager->get('ViewHelperManager');
$viewHelperManager->setInvokableClass('headmeta', 'MyNamespace\View\Helper\HeadMeta');
}
...
public function getAutoloaderConfig() {
return array(
...
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
'MyNamespace' => __DIR__ . '/../../vendor/MyNamespace/library/MyNamespace',
),
),
);
}
}
Now I'm having a problem with a bug in the Zend\Paginator\Adapter\DbSelect. It has already been fixed, but the fix has not been merged to the master branch yet. Anyway, I want to switch temporarily to my own DbSelect class. But DbSelect is not invocable. How to use a custom class insteead of a default framework class, e.g. Zend\Paginator\Adapter\DbSelect?
Paginator has its own adapter plugin manager. So you can push to him your own dbselect factory.
I am building the ZF2 Album tutorial application and when I unit test I am consistently receiving the same error even though I've rebuilt the application again. Can someone tell me what is going on here? I am dumping all relevant information here to assist. The error is:
PHPUnit 3.7.10 by Sebastian Bergmann.
Configuration read from D:\PHP\zf2-tutorial\module\Album\test\phpunit.xml.dist
......E
Time: 0 seconds, Memory: 6.25Mb
There was 1 error:
1) AlbumTest\Model\AlbumTableTest::testGetAlbumTableReturnsAnInstanceOfAlbumTable
Undefined property: AlbumTest\Model\AlbumTableTest::$controller
D:\PHP\zf2-tutorial\module\Album\test\AlbumTest\Model\AlbumTableTest.php:116
FAILURES!
Tests: 7, Assertions: 9, Errors: 1.
AlbumTableTest.php is as follows and the error is received on the final assertion:
<?php
namespace AlbumTest\Model;
use Album\Model\AlbumTable;
use Album\Model\Album;
use Zend\Db\ResultSet\ResultSet;
use PHPUnit_Framework_TestCase;
class AlbumTableTest extends PHPUnit_Framework_TestCase {
public function testFetchAllReturnsAllAlbums() {
$resultSet = new ResultSet();
$mockTableGateway = $this->getMock('Zend\Db\TableGateway\TableGateway', array('select'), array(), '', false);
$mockTableGateway->expects($this->once())
->method('select')
->with()
->will($this->returnValue($resultSet));
$albumTable = new AlbumTable($mockTableGateway);
$this->assertSame($resultSet, $albumTable->fetchAll());
}
public function testCanRetrieveAnAlbumByItsId() {
$album = new Album();
$album->exchangeArray(array('id' => 123,
'artist' => 'The Military Wives',
'title' => 'In My Dreams'));
$resultSet = new ResultSet();
$resultSet->setArrayObjectPrototype(new Album());
$resultSet->initialize(array($album));
$mockTableGateway = $this->getMock('Zend\Db\TableGateway\TableGateway', array('select'), array(), '', false);
$mockTableGateway->expects($this->once())
->method('select')
->with(array('id' => 123))
->will($this->returnValue($resultSet));
$albumTable = new AlbumTable($mockTableGateway);
$this->assertSame($album, $albumTable->getAlbum(123));
}
public function testCanDeleteAnAlbumByItsId() {
$mockTableGateway = $this->getMock('Zend\Db\TableGateway\TableGateway', array('delete'), array(), '', false);
$mockTableGateway->expects($this->once())
->method('delete')
->with(array('id' => 123));
$albumTable = new AlbumTable($mockTableGateway);
$albumTable->deleteAlbum(123);
}
public function testSaveAlbumWillInsertNewAlbumsIfTheyDontAlreadyHaveAnId() {
$albumData = array('artist' => 'The Military Wives', 'title' => 'In My Dreams');
$album = new Album();
$album->exchangeArray($albumData);
$mockTableGateway = $this->getMock('Zend\Db\TableGateway\TableGateway', array('insert'), array(), '', false);
$mockTableGateway->expects($this->once())
->method('insert')
->with($albumData);
$albumTable = new AlbumTable($mockTableGateway);
$albumTable->saveAlbum($album);
}
public function testSaveAlbumWillUpdateExistingAlbumsIfTheyAlreadyHaveAnId() {
$albumData = array('id' => 123, 'artist' => 'The Military Wives', 'title' => 'In My Dreams');
$album = new Album();
$album->exchangeArray($albumData);
$resultSet = new ResultSet();
$resultSet->setArrayObjectPrototype(new Album());
$resultSet->initialize(array($album));
$mockTableGateway = $this->getMock('Zend\Db\TableGateway\TableGateway', array('select', 'update'), array(), '', false);
$mockTableGateway->expects($this->once())
->method('select')
->with(array('id' => 123))
->will($this->returnValue($resultSet));
$mockTableGateway->expects($this->once())
->method('update')
->with(array('artist' => 'The Military Wives', 'title' => 'In My Dreams'), array('id' => 123));
$albumTable = new AlbumTable($mockTableGateway);
$albumTable->saveAlbum($album);
}
public function testExceptionIsThrownWhenGettingNonexistentAlbum() {
$resultSet = new ResultSet();
$resultSet->setArrayObjectPrototype(new Album());
$resultSet->initialize(array());
$mockTableGateway = $this->getMock('Zend\Db\TableGateway\TableGateway', array('select'), array(), '', false);
$mockTableGateway->expects($this->once())
->method('select')
->with(array('id' => 123))
->will($this->returnValue($resultSet));
$albumTable = new AlbumTable($mockTableGateway);
try {
$albumTable->getAlbum(123);
} catch (\Exception $e) {
$this->assertSame('Could not find row 123', $e->getMessage());
return;
}
$this->fail('Expected exception was not thrown');
}
public function testGetAlbumTableReturnsAnInstanceOfAlbumTable() {
$this->assertInstanceOf('Album\Model\AlbumTable', $this->controller->getAlbumTable());
}
}
?>
getAlbumTable is in AlbumController as follows:
<?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(),
));
}
public function addAction() {
}
public function editAction() {
}
public function deleteAction() {
}
public function getAlbumTable() {
if (!$this->albumTable) {
$sm = $this->getServiceLocator();
$this->albumTable = $sm->get('Album\Model\AlbumTable');
}
return $this->albumTable;
}
}
?>
And AlbumTable is:
<?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('Form id does not exist');
}
}
}
public function deleteAlbum($id)
{
$this->tableGateway->delete(array('id' => $id));
}
}
?>
Module.php is:
<?php
namespace Album;
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';
}
// Add this method:
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);
},
),
);
}
}
?>
module.config.php is:
<?php
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',
),
),
);
?>
application.config.php is:
<?php
return array(
'modules' => array(
'Application',
'Album', // <-- Add this line
),
'module_listener_options' => array(
'config_glob_paths' => array(
'config/autoload/{,*.}{global,local}.php',
),
'module_paths' => array(
'./module',
'./vendor',
),
),
);
?>
Bootstrap.php:
<?php
namespace AlbumTest;//Change this namespace for your test
use Zend\Loader\AutoloaderFactory;
use Zend\Mvc\Service\ServiceManagerConfig;
use Zend\ServiceManager\ServiceManager;
use Zend\Stdlib\ArrayUtils;
use RuntimeException;
error_reporting(E_ALL | E_STRICT);
chdir(__DIR__);
class Bootstrap
{
protected static $serviceManager;
protected static $config;
protected static $bootstrap;
public static function init()
{
// Load the user-defined test configuration file, if it exists; otherwise, load
if (is_readable(__DIR__ . '/TestConfig.php')) {
$testConfig = include __DIR__ . '/TestConfig.php';
} else {
$testConfig = include __DIR__ . '/TestConfig.php.dist';
}
$zf2ModulePaths = array();
if (isset($testConfig['module_listener_options']['module_paths'])) {
$modulePaths = $testConfig['module_listener_options']['module_paths'];
foreach ($modulePaths as $modulePath) {
if (($path = static::findParentPath($modulePath)) ) {
$zf2ModulePaths[] = $path;
}
}
}
$zf2ModulePaths = implode(PATH_SEPARATOR, $zf2ModulePaths) . PATH_SEPARATOR;
$zf2ModulePaths .= getenv('ZF2_MODULES_TEST_PATHS') ?: (defined('ZF2_MODULES_TEST_PATHS') ? ZF2_MODULES_TEST_PATHS : '');
static::initAutoloader();
// use ModuleManager to load this module and it's dependencies
$baseConfig = array(
'module_listener_options' => array(
'module_paths' => explode(PATH_SEPARATOR, $zf2ModulePaths),
),
);
$config = ArrayUtils::merge($baseConfig, $testConfig);
$serviceManager = new ServiceManager(new ServiceManagerConfig());
$serviceManager->setService('ApplicationConfig', $config);
$serviceManager->get('ModuleManager')->loadModules();
static::$serviceManager = $serviceManager;
static::$config = $config;
}
public static function getServiceManager()
{
return static::$serviceManager;
}
public static function getConfig()
{
return static::$config;
}
protected static function initAutoloader()
{
$vendorPath = static::findParentPath('vendor');
if (is_readable($vendorPath . '/autoload.php')) {
$loader = include $vendorPath . '/autoload.php';
} else {
$zf2Path = getenv('ZF2_PATH') ?: (defined('ZF2_PATH') ? ZF2_PATH : (is_dir($vendorPath . '/ZF2/library') ? $vendorPath . '/ZF2/library' : false));
if (!$zf2Path) {
throw new RuntimeException('Unable to load ZF2. Run `php composer.phar install` or define a ZF2_PATH environment variable.');
}
include $zf2Path . '/Zend/Loader/AutoloaderFactory.php';
}
AutoloaderFactory::factory(array(
'Zend\Loader\StandardAutoloader' => array(
'autoregister_zf' => true,
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/' . __NAMESPACE__,
),
),
));
}
protected static function findParentPath($path)
{
$dir = __DIR__;
$previousDir = '.';
while (!is_dir($dir . '/' . $path)) {
$dir = dirname($dir);
if ($previousDir === $dir) return false;
$previousDir = $dir;
}
return $dir . '/' . $path;
}
}
Bootstrap::init();
?>
TestConfig.php.dist:
<?php
return array(
'modules' => array(
'Album',
),
'module_listener_options' => array(
'config_glob_paths' => array(
'../../../config/autoload/{,*.}{global,local}.php',
),
'module_paths' => array(
'module',
'vendor',
),
),
);
?>
And, finally, phpunit.xml.dist:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="Bootstrap.php">
<testsuites>
<testsuite name="zf2tutorial">
<directory>./AlbumTest</directory>
</testsuite>
</testsuites>
</phpunit>
You are correct to assume that you need to add some setup code and comparing it with AlbumControllerTest.php is a good idea.
As the error message states, the issue is that the AlbumTableTest object does not have controller property. We therefore need to add the property using:
$protected controller
and initialise it using:
$this->controller = new AlbumController()
In addition, we need to initialise the serviceManager property and set its serviceLocator property so that the following calls make sense in the getAlbumTable method of the controller:
$sm = $this->getServiceLocator();
$this->albumTable = $sm->get('Album\Model\AlbumTable');
To summarise, you did the right thing but you didn't need all the additional code. You can get away with:
use AlbumTest\Bootstrap;
use Album\Controller\AlbumController;
use Album\Model\AlbumTable;
use Album\Model\Album;
use Zend\Db\ResultSet\ResultSet;
use PHPUnit_Framework_TestCase;
class AlbumTableTest extends PHPUnit_Framework_TestCase
{
protected $controller;
protected function setUp()
{
$serviceManager = Bootstrap::getServiceManager();
$this->controller = new AlbumController();
$this->controller->setServiceLocator($serviceManager);
}
....
at the start of AlbumTableTest.php
While I am not certain that this is the appropriate fix at this point, I resolved the error. I looked into AlbumControllerTest as opposed to AlbumTableTest. It has a setup method that creates the controller class. I copied the setup code along with the appropriate use statements and variable declarations and, for the moment, I am on to the next issue...
I'm still interested in a better answer!
What I copied (added) includes:
use AlbumTest\Bootstrap;
use Album\Controller\AlbumController;
use Zend\Http\Request;
use Zend\Http\Response;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\RouteMatch;
use Zend\Mvc\Router\Http\TreeRouteStack as HttpRouter;
use PHPUnit_Framework_TestCase;
class AlbumTableTest extends PHPUnit_Framework_TestCase {
protected $controller;
protected $request;
protected $response;
protected $routeMatch;
protected $event;
protected function setUp()
{
$serviceManager = Bootstrap::getServiceManager();
$this->controller = new AlbumController();
$this->request = new Request();
$this->routeMatch = new RouteMatch(array('controller' => 'index'));
$this->event = new MvcEvent();
$config = $serviceManager->get('Config');
$routerConfig = isset($config['router']) ? $config['router'] : array();
$router = HttpRouter::factory($routerConfig);
$this->event->setRouter($router);
$this->event->setRouteMatch($this->routeMatch);
$this->controller->setEvent($this->event);
$this->controller->setServiceLocator($serviceManager);
}
You forgot to add the new import statements in Module.php. The start of the file should look like this:
namespace Album;
use Album\Model\Album;
use Album\Model\AlbumTable;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
class Module
{
//...
Easy to skip, hard to find, I've spent good 15 minutes on the same thing...