Codeigniter 2 und Doctrine 2 HowTo 1/5
Ziel:
- Codeigniter 2 mit Doctrine 2 installieren
- Klasse erstellen und Datenbank anlegen
- Instanz einer Klasse erzeugen
- Containment Beziehung nutzen
- Containment Beziehung auslesen
1. Codeigniter 2 mit Doctrine 2 installieren
————-
Info: Die Installation und der Code für die Doctrine integration stammen ursprünglich von dieser Seite (Installation sehr ausführlich erklärt):
http://wildlyinaccurate.com/integrating-doctrine-2-with-codeigniter-2/
————-
Nach dem Download von Codeigniter Version 2.0.2 ergeben sich zwei Ordner:
„system“ und „application“.
Zusätzlich wird Doctrine 2.0.4 geladen.
Entpackt ergeben sich die Ordner „bin“ und „doctrine“.
Der „doctrine“ Ordner wird komplett ins Codeigniter Verzeichnis „/application/libraries“ kopiert.
Zur Verwendung von Doctrine 2 fehlt eine Klasse mit die mit Codeigniter genutzt werden kann.
/* use with
* $em = $this->doctrine->em;
*/
use Doctrine\Common\ClassLoader,
Doctrine\ORM\Configuration,
Doctrine\ORM\EntityManager,
Doctrine\Common\Cache\ArrayCache,
Doctrine\DBAL\Logging\EchoSqlLogger;
class Doctrine {
public $em = null;
public function __construct()
{
// load database configuration from CodeIgniter
require_once APPPATH.'config/database.php';
// Set up class loading. You could use different autoloaders, provided by your favorite framework,
// if you want to.
require_once APPPATH.'libraries/Doctrine/Common/ClassLoader.php';
$doctrineClassLoader = new ClassLoader('Doctrine', APPPATH.'libraries');
$doctrineClassLoader->register();
$entitiesClassLoader = new ClassLoader('models', rtrim(APPPATH, "/" ));
$entitiesClassLoader->register();
$proxiesClassLoader = new ClassLoader('Proxies', APPPATH.'models/proxies');
$proxiesClassLoader->register();
// Set up caches
$config = new Configuration;
$cache = new ArrayCache;
$config->setMetadataCacheImpl($cache);
$config->setQueryCacheImpl($cache);
// Proxy configuration
$config->setProxyDir(APPPATH.'/models/proxies');
$config->setProxyNamespace('Proxies');
// Set up logger
$logger = new EchoSqlLogger;
$log = 0;
if($log){
$config->setSqlLogger($logger);
}
$config->setAutoGenerateProxyClasses( TRUE );
// Database connection information
$connectionOptions = array(
'driver' => $db['default']['dbdriver'],
'user' => $db['default']['username'],
'password' => $db['default']['password'],
'host' => $db['default']['hostname'],
'dbname' => $db['default']['database']
);
// Mapping Configuration
// $driverImpl = $config->newDefaultAnnotationDriver(APPPATH.'/application/models');
// $config->setMetadataDriverImpl($driverImpl);
// Set up driver
$Doctrine_AnnotationReader = new \Doctrine\Common\Annotations\AnnotationReader($cache);
$Doctrine_AnnotationReader->setDefaultAnnotationNamespace('Doctrine\ORM\Mapping\');
$driver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($Doctrine_AnnotationReader, APPPATH.'models');
$config->setMetadataDriverImpl($driver);
// Create EntityManager
$this->em = EntityManager::create($connectionOptions, $config);
}
}
?>
Dieser Code wird in einer Datei gespeichert (doctrine.php) und im Ordner „application/libraries/“ abgelegt.
Zusätzlich fehlt eine Datei zum Initiieren der Tabellen in der Datenbanken.
chdir(dirname(__FILE__) . '/libraries');
require_once 'Doctrine/Common/ClassLoader.php';
$classLoader = new \Doctrine\Common\ClassLoader('Doctrine');
$classLoader->register();
$classLoader = new \Doctrine\Common\ClassLoader('Symfony', 'Doctrine');
$classLoader->register();
$configFile = '../cli_config.php';
$helperSet = null;
if (file_exists($configFile)) {
if ( ! is_readable($configFile)) {
trigger_error(
'Configuration file [' . $configFile . '] does not have read permission.', E_ERROR
);
}
require $configFile;
foreach ($GLOBALS as $helperSetCandidate) {
if ($helperSetCandidate instanceof \Symfony\Component\Console\Helper\HelperSet) {
$helperSet = $helperSetCandidate;
break;
}
}
}
$helperSet = ($helperSet) ?: new \Symfony\Component\Console\Helper\HelperSet();
$cli = new \Symfony\Component\Console\Application('Doctrine Command Line Interface', Doctrine\ORM\Version::VERSION);
$cli->setCatchExceptions(true);
$cli->setHelperSet($helperSet);
$cli->addCommands(array(
// DBAL Commands
new \Doctrine\DBAL\Tools\Console\Command\RunSqlCommand(),
new \Doctrine\DBAL\Tools\Console\Command\ImportCommand(),
// ORM Commands
new \Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand(),
new \Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand(),
new \Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand(),
new \Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand(),
new \Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand(),
new \Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand(),
new \Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand(),
new \Doctrine\ORM\Tools\Console\Command\ConvertDoctrine1SchemaCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateRepositoriesCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateEntitiesCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand(),
new \Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand(),
new \Doctrine\ORM\Tools\Console\Command\RunDqlCommand(),
new \Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand(),
));
$cli->run();
?>
Dieser Code wird als Datei doctrine_init.php unter „application/“ abgelegt.
Die letzte Datei für Doctrine 2 ist die Konfiguration.
use Doctrine\Common\ClassLoader,
Doctrine\ORM\Configuration,
Doctrine\ORM\EntityManager,
Doctrine\Common\Cache\ArrayCache,
Doctrine\DBAL\Logging\EchoSqlLogger;
define('BASEPATH', __DIR__ . '/../system/');
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/libraries/Doctrine/Common/ClassLoader.php';
$doctrineClassLoader = new ClassLoader('Doctrine', __DIR__.'libraries');
$doctrineClassLoader->register();
$entitiesClassLoader = new ClassLoader('models', __DIR__);
$entitiesClassLoader->register();
$proxiesClassLoader = new ClassLoader('Proxies', __DIR__.'models/proxies');
$proxiesClassLoader->register();
$config = new \Doctrine\ORM\Configuration();
$config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache);
$config->setProxyDir(__DIR__ . '/Proxies');
$config->setProxyNamespace('Proxies');
$cache = new ArrayCache;
// Set up driver
$Doctrine_AnnotationReader = new \Doctrine\Common\Annotations\AnnotationReader($cache);
$Doctrine_AnnotationReader->setDefaultAnnotationNamespace('Doctrine\ORM\Mapping\');
$driver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($Doctrine_AnnotationReader, realpath('../models'));
$config->setMetadataDriverImpl($driver);
// Database connection information
$connectionOptions = array(
'driver' => 'pdo_mysql',
'user' => $db['default']['username'],
'password' => $db['default']['password'],
'host' => $db['default']['hostname'],
'dbname' => $db['default']['database']
);
$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);
$helperSet = new \Symfony\Component\Console\Helper\HelperSet(array(
'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()),
'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em)
));
?>
Der Code wird als „cli_config.php“ unter dem Ordner „application/“ abgelegt.
Mit den drei zusätzlichen Dateien sind alle Dateien für Doctrine 2 vorhanden.
Es folgt die Konfiguration in Codeigniter
Die Datei database.php muss im Ordner „application/config“ konfiguriert werden.
Natürlich muss jetzt noch die „base_url“ in der „application/config/config.php“ Datei eingestellt werden.
Great tutorials. Thanks Burak!Question: I am a niwbee to MVC, CI and Doctrine, so maybe my question is not that relevant. But shouldnt the CRUD methods be located inside the Model rather than the Controller? I know we are not using the CI Models and hence putting the CRUD in Doctrine Model would cause complications. But I was wondering if the alternative of putting the CRUD code in the controller is a good practice or not?Cheers