I am new to zend framework. I have created "models" folder in application directory. Inside models folder I created a class Application_Models_Albums
which extends Zend_Db_Table_Abstract
.
Now when I use the following code in IndexController. I get error:
$albums = new Application_Models_Albums();
$this->view->albums = $albums->fetchAll();
Error: Fatal error: Class 'Application_Models_Albums' not found in H:\Documents\IIS Server Root\localhost\learning开发者_如何学JAVA\zf1\application\controllers\IndexController.php on line 13
Please help. How can I load models in zend framework?
You need to name your model Albums. and save in models/albums.php
The auto-loader will figure out where to load it from by the name. so even though the model is named albums
, you call it by new Application_Models_Albums()
The autoloader find it in application/models/albums.php
similarly the Zend_Db_Table_Abstract
class is located in Zend/Db/Table/Abstract.php
edit
IF you cant get the autoloader to work, you can do it the quick and easy way by just adding models/
to your include path. I've done this before and it works fine.
Something like set_include_path(get_include_path().PATH_SEPERATOR."models/")
in your index.php
Your model class name should be Application_Model_Albums
- with Model
in singular.
See http://framework.zend.com/manual/en/zend.loader.autoloader-resource.html for more info on Zend Autoloader.
you need to require your model class-
require_once 'PathToModel\Application_Models_Albums.php';
some people create autoloader classes to deal with this, YMMV
It sounds like your Bootstrap
or application.ini
needs to specify the namespace as 'Application_'.
In Bootstrap.php
:
protected function _initAutoloader()
{
$autoloader = new Zend_Application_Module_Autoloader(array(
'basePath' => APPLICATION_PATH,
'namespace' => 'Kwis_',
));
return $autoloader;
}
Alernatively, in configs/application.ini
:
appnamespace = "Application_"
You could also extend Zend_Controller_Action and add a method like this:
protected $_tables = array();
protected function _getTable($table)
{
if (false === array_key_exists($table, $this->_tables)) {
require_once(APPLICATION_PATH.'/modules/'.$this->_request->getModuleName().'/models/'.$table.'.php');
$this->_tables[$table] = new $table();
}
return $this->_tables[$table];
}
精彩评论