7 minutes reading time (1463 words)

Using Doctrine ORM in Joomla!

Joomla is a decent CMS with very nice features. It works great for the end user and has many components ready to use from the online world. What I don't like personally, as a developer, is the model implementation in Joomla. For me the way ' model and table' classes are implemented, just doesn't feel right to me. Also it is very difficult to get other models in a controller or an other model class. With Symfony I have worked with Doctrine regularly and in this blog I'll show you how to use Doctrine for your own component in Joomla. Doctrine is an Object Relational  Mapping framework and offers you a persistence library. This not the holy grail and you should determine  if you need the extra overhead and if you are comfortable with it.

 

The first step

I'll start with an clean Joomla 1.6 install from the Joomla website. Also I installed Doctrine ORM from the Doctrine website. I unpacked the archive in  a new folder in the Joomla folder libraries.The structure in this new folder would be the same as the archive, so you get a Doctrine folder and a bin folder in the libraries/doctrine folder. By the way, we live in 2011 and the current release of PHP is 5.3.5. Doctrine and the implementation I show you here assumes you use PHP 5.3. If you still use PHP 5.2 you seriously need to work on the upgrade of that projects.

The example

I'm going to provide you a very simple example. The most important thing I want to show you is how to implement Doctrine in your Joomla project, not how to use Doctrine. The documentation on the Doctrine website is of high quality and should give you enough information to get going. We are writing a new component called Bugs end hold one entity called 'Bug'. It has five attributes. ID, title, description, notificationDate and solvedDate. In the controller I'll show you some examples how to use it.

Setting up the defaults

It is possible that you want to use Doctrine on multiple components you are going to write. This is the reason why I choose to add Doctrine to the libraries folder. In this folder we are going to add two files. One is an interface to provide a generic interface, the other is a bootstrapper to get Doctrine going. First the easy stuff, the interface. The interface looks like this: {codecitation style="brush: javascript;"} interface JoomlaDoctrineController { public function setEntityManager(Doctrine\ORM\EntityManager $entityManager); {/codecitation} Nothing spectacular  here, lets move on. Doctrine needs to have some basic configuration to get going. We need to tell Doctrine where it can find the entities and where it needs to place the generated proxies. Here is the implementation of JoomlaDoctrineBootstrapper: {codecitation style="brush: javascript;"} /** * Configuration class to integrate Doctrine into Joomla. * * @author pderaaij */ use Doctrine\Common\ClassLoader, Doctrine\ORM\EntityManager, Doctrine\ORM\Configuration, Doctrine\Common\Cache\ArrayCache; if( !class_exists('\Doctrine\Common\Classloader')) { require_once dirname(__FILE__) . '/../doctrine/Doctrine/Common/ClassLoader.php'; } class JoomlaDoctrineBootstrapper { const APP_MODE_DEVELOPMENT = 1; const APP_MODE_PRODUCTION = 2; private $applicationMode; private $cache; private $entityLibrary; private $proxyLibrary; private $proxyNamespace; private $entityManager; private $connectionOptions; public function __construct($applicationMode) { $this->applicationMode = $applicationMode; } public function getConnectionOptions() { return $this->connectionOptions; } public function setConnectionOptions($connectionOptions) { $this->connectionOptions = $connectionOptions; } public function getProxyLibrary() { return $this->proxyLibrary; } public function setProxyLibrary($proxyLibrary) { $this->proxyLibrary = $proxyLibrary; } public function getProxyNamespace() { return $this->proxyNamespace; } public function setProxyNamespace($proxyNamespace) { $this->proxyNamespace = $proxyNamespace; } public function getCache() { return $this->cache; } public function setCache($cache) { $this->cache = $cache; } public function getEntityLibrary() { return $this->entityLibrary; } public function setEntityLibrary($entityLibrary) { $this->entityLibrary = $entityLibrary; } public function getApplicationMode() { return $this->applicationMode; } public function setApplicationMode($applicationMode) { $this->applicationMode = $applicationMode; } public function getEntityManager() { return $this->entityManager; } public function setEntityManager($entityManager) { $this->entityManager = $entityManager; } /** * Bootstrap Doctrine, setting the libraries and namespaces and creating * the entitymanager */ public function bootstrap() { $this->registerClassLoader(); // Load cache if ($this->getApplicationMode() == self::APP_MODE_DEVELOPMENT) { $this->cache = new ArrayCache; } else { $this->cache = new ApcCache; } /** @var $config Doctrine\ORM\Configuration */ $config = new Configuration; $config->setMetadataCacheImpl($this->cache); $driverImpl = $config->newDefaultAnnotationDriver($this->getEntityLibrary()); $config->setMetadataDriverImpl($driverImpl); $config->setQueryCacheImpl($this->cache); $config->setProxyDir($this->getProxyLibrary()); $config->setProxyNamespace($this->getProxyNamespace()); if ($this->applicationMode == self::APP_MODE_DEVELOPMENT) { $config->setAutoGenerateProxyClasses(true); } else { $config->setAutoGenerateProxyClasses(false); } $this->entityManager = EntityManager::create($this->getConnectionOptions(), $config); } /** * Register the different classloaders for each type. */ private function registerClassLoader() { // Autoloader for all the Doctrine library files $classLoader = new ClassLoader('Doctrine', dirname(__FILE__) . '/'); $classLoader->register(); // Autoloader for all Entities $modelLoader = new ClassLoader('Entities', $this->getEntityLibrary()); $modelLoader->register(); // Autoloader for all Proxies $proxiesClassLoader = new ClassLoader('Proxies', $this->getProxyLibrary()); $proxiesClassLoader->register(); } } {/codecitation}
Okay, what's going on here. As said earlier we are expecting an PHP 5.3 application, so we are making a lot of use of namespaces here. We are loading some base classes of Doctrine so we can bootstrap it.
You see two constants in this class. These constants are flags you can use to set the environment the application is in. Is the application is used in a production environment it will make use of the APC cache. In development it will use a simple ArrayCache which is volatile.
If we skip the getters and setters we see two interesting functions. The first one is registerClassLoader. Here we register three classloaders. The first one is used to auto load all Doctrine classes. The second one we use for the entities we created. The proxies are auto loaded by the third class loader. The argument the last two classloaders receive are just absolute paths to the folder containing the belonging files.
In the bootstrap function we define the configuration for Doctrine. We define the cache it needs to use, the AnnotationDriver and the folders where Doctrine can find proxies and entities. To learn more about this configuration you should read the Doctrine manual. What we do here is a standard configuration, setting the right locations.

Creating the component

Now we can start with setting up our component. Create a com_bugs folder in components with a models folder in it. In the models folder you should create an Entities folder (mind the capital, it's important!). Create the 'Bug' entity next. Copy the text below and place it in Bug.php in the models/Entities folder. Do not forget to set the namespace it is essential. If you forget it the entity can't be found by the classloader. This is also the reason why the capitalization is so important. {codecitation style="brush: javascript;"} namespace Entities; /** * @Entity @Table(name="bugs") */ class Bug { /** @Id @Column(type="integer") @GeneratedValue */ private $id; /** @Column(type="string") */ private $title; /** @Column(type="string") */ private $description; /** @Column(type="datetime") */ private $notificationDate; /** @Column(type="datetime") */ private $solvedDate; public function getId() { return $this->id; } public function setId($id) { $this->id = $id; } public function getTitle() { return $this->title; } public function setTitle($title) { $this->title = $title; } public function getDescription() { return $this->description; } public function setDescription($description) { $this->description = $description; } public function getNotificationDate() { return $this->notificationDate; } public function setNotificationDate($notificationDate) { $this->notificationDate = $notificationDate; } public function getSolvedDate() { return $this->solvedDate; } public function setSolvedDate($solvedDate) { $this->solvedDate = $solvedDate; } } {/codecitation} There is our entity! Now we need a way to get that entity definition in our database. Doctrine has command-line tools for us to do that, but they need the same configuration as we give to our controller in the front-end. So, lets set-up that configuration and use it on the command line.

The configuration

In order to use Doctrine within our controllers we have to create the configuration and use our created bootstrapper to get Doctrine going. At the moment I chose the component initialization file for our initialization work on Doctrine. I'm looking for a way to extract this initialization in to a nicer place, but the options I've tried didn't made me happy at all. What do we need to do? Well, we need to tell where our entities are stored on the file system and where we want to store our proxy files. also we need to pass our database parameters to Doctrine so it has authorization to the database. Here is my init file (bugs.php) of the component: {codecitation style="brush: javascript;"} // no direct access defined('_JEXEC') or die; // Include dependancies jimport('joomla.application.component.controller'); require_once(JPATH_LIBRARIES . '/doctrine/bootstrap.php'); $controller = JController::getInstance('Bugs'); // configure Doctrine thru the bootstrapper $controller->setEntityManager(bootstrapDoctrine()); $controller->execute(JRequest::getCmd('task', 'index')); $controller->redirect(); /** * Initialize doctrine by setting the entities and proxies locaties. Also define * a default namespace for the proxies. */ function bootstrapDoctrine() { $doctrineProxy = new JoomlaDoctrineBootstrapper( JoomlaDoctrineBootstrapper::APP_MODE_DEVELOPMENT ); $doctrineProxy->setEntityLibrary(dirname(__FILE__) . '/models'); $doctrineProxy->setProxyLibrary(dirname(__FILE__) . '/proxies'); $doctrineProxy->setProxyNamespace('Joomla\Proxies'); $doctrineProxy->setConnectionOptions(getConfigurationOptions()); $doctrineProxy->bootstrap(); return $doctrineProxy->getEntityManager(); } function getConfigurationOptions() { // Define database configuration options $joomlaConfig = JFactory::getConfig(); return array( 'driver' => 'pdo_mysql', 'path' => 'database.mysql', 'dbname' => $joomlaConfig->get('db'), 'user' => $joomlaConfig->get('user'), 'password' => $joomlaConfig->get('password') ); } {/codecitation}

It's a wrap

That's it, now you can make use of Doctrine within your component. It was a long blog post, but I hope I've shown you an easy way to get going with Doctrine within Joomla. I hope you liked this article. You can leave your feedback behind on this blog, since I'm always interested in new insights which I can use to learn and grow as an developer.
0
Joomla! Voices Heard Around the World
 

Comments

Already Registered? Login Here
No comments made yet. Be the first to submit a comment

By accepting you will be accessing a service provided by a third-party external to https://magazine.joomla.org/