Using Doctrine with Zend framework

Copy Doctrine.php and Doctrine folder to library folder.

Now add following function to your Bootstrap.php file.

public function _initDoctrine(){
require_once 'Doctrine.php';
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->pushAutoloader(array('Doctrine','autoload'));
$manager = Doctrine_Manager::getInstance();
$options = $this->getOptions(); // zf application config array
$dsn = $options['dsn'];
$conn = Doctrine_Manager::connection($dsn, 'defaultConn');
Doctrine_Core::generateModelsFromDb(APPLICATION_PATH.'/models',
array('defaultConn'),
array(
'generateBaseClasses' => true,
'generateTableClasses'=> true,
'classPrefix'=>'Model_',
'classPrefixFiles'=> false,
'baseClassesDirectory'=> '.'
)
);
}

The above code creates your Doctrine connection, so else where in your code you can use $conn = Doctrine_Manager::connection($dsn, ‘defaultConn’); to get a connections to database.

Also the above code gets DSN setting for you database which looks like dsn = “mysql://username:password@host/database_name” in your application.ini file.

The function Doctrine_Core::generateModelsFromDb with above settings will generate table and record classes for all the tables in your database and would save them to your application/models folder.

As all the classes generated by Doctrine would be prefixed with “Model_” you can would be able to use them anywhere in your Zend framework application because of ZF autoloader. As the above generated class would follow ZF convention for models.

Leave a Reply

Your email address will not be published. Required fields are marked *