Building Joomla component with Doctrine, adding views – Part 2

Posted by Siim on March 4th, 2010

In my previous post we set up initial structure for the component and generated models. Now it’s time to add some front-end views. I’ll show you how Doctrine can be used in controllers and how to create clean and simple views.

When using Joomla pattern, then most of the work is done in view’s display() method. I don’t like that. I’d like that my controller provides needed data to the view. So we need to create a base controller from which our component controllers inherit to provide an injection point for our views. View is created in controller’s display() method so we need to override that but most of the code remains same, though.

protected abstract function onViewLoaded(MvViewBase $view);

public function display($cachable=false)
{
	$document = JFactory::getDocument();

	$viewType = $document->getType();
	$viewName = ucfirst(JRequest::getCmd('view', 'topic'));
	$viewLayout	= JRequest::getCmd('layout', 'default');

	$view = $this->getView($viewName, $viewType, '', array('base_path' => $this->_basePath));

	// Set the layout
	$view->setLayout($viewLayout);

	// Display the view
	if ($cachable && $viewType != 'feed')
	{
		global $option;
		$cache = JFactory::getCache($option, 'view');
		$cache->get($view, 'display');
	}
	else
	{
		$this->onViewLoaded($view);
		$view->display();
	}
}

public function getModel($name='', $prefix='', $config=array())
{
	return false;
}

So now controller can be very simple – only load data using Doctrine and initialize the view. Views contains also only setters and getters for the data they need.

class Controller extends MvControllerBase
{
	protected function onViewLoaded(MvViewBase $view)
	{
		switch($view->getName())
		{
			case 'movies':
				$this->dataBindMoviesView($view);
				break;

			case 'movie':
				$this->dataBindMovieView($view);
				break;
		}
	}

	private function dataBindMoviesView(ViewMovies $view)
	{
		$query = Doctrine_Query::create()
				->select('m.*')
				->from('JosMvMovie m')
				->orderBy('m.title ASC');

		$movies = $query->execute();
		$view->setMovies($movies->getData());
	}

	private function dataBindMovieView(ViewMovie $view)
	{
		$movieId = JRequest::getInt('id', 0);
		$movie = Doctrine_Core::getTable('JosMvMovie')->find($movieId);

		$view->setMovie($movie);
	}
}

Doctrine (like most of the ORMs) can load related data automatically so no extra work needed for that. In our case, I can just ask genres from the movie, I don’t need to load them separately. Doctrine also allows tuning how and when relations are loaded – are they lazy-loaded or joined directly when executing query, for example. You can read more from here and here.

Because we have many-to-many relation between movies and genres, automatically generated models need some tuning. We have to specify the relation class name so that Doctrine can detect how it can fill the collections. When looking the definition of BaseJosMvMovie class, which contains mappings with the data model, then there is:

public function setUp()
{
	parent::setUp();
	$this->hasMany('JosMvMovieGenre', array(
		 'local' => 'genre_id',
		 'foreign' => 'genre_id'));
}

We need to add refClass attribute there which defines the class for many-to-many relation.

public function setUp()
{
	parent::setUp();
	$this->hasMany('JosMvGenre as Genres', array(
		 'local' => 'movie_id',
		 'foreign' => 'genre_id',
		 'refClass' => 'JosMvMovieGenre'));
}

Same kind of change needs to be done with the BaseJosMvGenre too, if you want access movies from the genre. Now we only need to add some views to display our movies. They are dead simple.

class ViewMovies extends MvViewBase
{
	private $_movies;

	public function setMovies(array $movies)
	{
		$this->_movies = $movies;
	}

	public function getMovies()
	{
		return $this->_movies;
	}
}

And HTML for that.

<table width="100%" border="1">
	<caption>Movies</caption>
<thead>
<tr>
	<th>Title</th>
	<th>IMDB</th>
	<th>Genres</th>
</tr>
</thead>
<tbody>
<?php foreach($this->getMovies() as $movie): ?>
<tr>
	<td title="<?php echo $movie->plot; ?>"><a href="<?php echo $this->getRouter()->createMovieLink($movie); ?>"><?php echo $movie->title; ?></a></td>
	<td><a href="<?php echo $movie->imdb_link; ?>" target="_blank">IMDB</a></td>
	<td><?php echo join(', ', $movie->Genres->getData()); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

So this is it for now. Hope it gets you started. In my next post in the series I’ll create views for the back-end, there are things a little bit different, but not much. Full source code with both the views can be downloaded here.

Building Joomla component with Doctrine – Part 1

Posted by Siim on March 1st, 2010

I have done plenty of development on Joomla platform. Although generally it’s pretty good CMS platform for PHP but the part of that I don’t like is it’s MVC implementation. The Model implementation feels just so weird to me. Maybe because I haven’t used to that approach it uses, because I’m more NHibernate guy from .NET space… Anyway, I decided to look for ORMs in a PHP environment and found Doctrine. I did a simple test project with that and decided to use it to develop a simple Joomla component and keep things as simple as possible.

In it’s standard implementation of MVC in Joomla, controller injects needed models to the view and view asks data directly from the models. In other cases (when there is no need for a view) controller uses models directly to accomplish some task. I don’t like that. I’d like when there is just a plain view which is filled with the data by the controller and I would loose the concept of model (in terms of Joomla) wholly. Model layer will be replaced with the Doctrine and it will be used only by the controller not views.

So lets start.

Sample component

For a sample component we use simple movies catalog. It contains models for Movie and Genre. Movie has attributes like name, plot and link to IMDB. Administrators can manage movies and genres from the back-end. From front-end users can browse movies and filter them by genre and name. This should me simple enough to start with. The purpose of this post is to demonstrate how to integrate Doctrine into Joomla, not to demonstrate capabilities of Doctrine. This is the data model:

movies_data_model

Firstly we need to install Doctrine under the Joomla libraries folder. You can download the latest stable version (which is 1.2.1) from here. After downloading extract the contents of the lib directory under Joomla libraries/doctrine directory.

Configuring Doctrine and creating models

First we need to configure Doctrine to use Joomla database settings. Interesting thing here is the table name format. Firstly we use the Joomla configured table name prefix. Secondly we add our own table prefix because we don’t want to use all the Joomla tables (at least in this case). Here is sample code.

$componentTablePrefix = 'mv_';
$config = JFactory::getConfig();
$ormManager = Doctrine_Manager::getInstance();
$ormManager->setAttribute(Doctrine_Core::ATTR_TBLNAME_FORMAT, $config->getValue('config.dbprefix').$componentTablePrefix.'%s');
$ormManager->setAttribute(Doctrine_Core::ATTR_AUTOLOAD_TABLE_CLASSES, true);
$ormManager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL);
$ormManager->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true);
$conn = Doctrine_Manager::connection(
    $config->getValue('config.dbtype').'://'.
    $config->getValue('config.user').':'.
    $config->getValue('config.password').'@'.
    $config->getValue('config.host').'/'.
    $config->getValue('config.db'), 'default');

Then we use Doctrine to generate object model from the database tables for us. Of course you can create (or update) them manually if you want, there’s a pretty good documentation on that. We use this command to do that.

$modelsPath = JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_movies'.DS.'models'.DS;
Doctrine_Core::generateModelsFromDb($modelsPath, array('default'), array('generateTableClasses' => true));
Doctrine_Core::loadModels($modelsPath);

Unfortunately Doctrine also adds table prefix to the class name. So table name jos_mv_movie is converted to class name JosMvMovie. Generally I would remove that but currently I leave it as it is.

Creating a component structure

Next we create a bootstrapper script for our component to do all the wiring for us. It will include setup for Doctrine and for our component. We use PHP spl_autoload_register function to provide functionality to load all necessary scripts automatically without the need to scatter our scripts with require statements. Because Joomla uses __autoload function, we also need to re-register Joomla autloader with spl_autoload_register. That’s because __autoload can be used only once but we need different autoload functions – for Doctrine, our component and for Joomla itself.

Note: Because of Joomla isn’t written for PHP5 specifically, you need to explicitly set JLoader::load function to static.

We will use the same bootstrapper for front-end and back-end so we need to create separate configuration options for those. Because in front-end we need to load classes that are found from the front-end directories but also classes that are defined in the back-end, whereas database configuration remains same. And when creating some integration tests you may want to connect to different database.

Here is part of the code for bootstrapper.

class MvBootstrapper
{
    private static $configurationMode;
    public static function configure(ConfigurationMode $mode)
    {
        self::$configurationMode = $mode;
        self::configureJoomla();
        self::configureMovies();
        self::configureDoctrine();
    }
    private static function getModelsPath()
    {
        $modelsPath = JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_movies'.DS.'models'.DS;
        return $modelsPath;
    }
    private static function configureJoomla()
    {
        spl_autoload_register('JLoader::load');
    }
    private static function configureDoctrine()
    {
        JLoader::register('Doctrine_Core', JPATH_SITE.DS.'libraries'.DS.'doctrine'.DS.'Doctrine'.DS.'Core.php');
        JLoader::load('Doctrine');
        spl_autoload_register('Doctrine_Core::autoload');
        $ormManager = Doctrine_Manager::getInstance();
        $ormManager->setAttribute(Doctrine_Core::ATTR_TBLNAME_FORMAT, self::$configurationMode->getTablePrefix().'%s');
        $ormManager->setAttribute(Doctrine_Core::ATTR_AUTOLOAD_TABLE_CLASSES, true);
        $ormManager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL);
        $ormManager->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true);
        $conn = Doctrine_Manager::connection(
            self::$configurationMode->getDbType().'://'.
            self::$configurationMode->getDbUsername().':'.
            self::$configurationMode->getDbPassword().'@'.
            self::$configurationMode->getDbHost().'/'.
            self::$configurationMode->getDbName(), 'default');
        Doctrine_Core::loadModels(self::getModelsPath());
    }
    private static function configureMovies()
    {
        MvBootstrapper::registerPath('base', self::$configurationMode);
        MvBootstrapper::registerPath('models/generated', ConfigurationMode::BackEnd());
        spl_autoload_register('MvBootstrapper::autoload');
    }
    public static function autoload($className)
    {
        // Autoload logic
    }
    private static function registerPath($path, ConfigurationMode $mode)
    {
        // Path registration logic
    }
}

Now we need to create startup scripts for our component. It’s nothing special, just a regular component starter page. Here is the code for front-end view.

defined('_JEXEC') or die('Restricted access');
require_once (JPATH_COMPONENT_ADMINISTRATOR.DS.'bootstrapper.php');
MvBootstrapper::configure(ConfigurationMode::FrontEnd());
require_once dirname(__FILE__).DS.'controller.php';
$className = 'Controller';
$controller = new $className();
$controller->execute(JRequest::getCmd('task'));
$controller->redirect();

That’s it for now. In my next post I’ll show how to create controllers and views for the front-end. And how to use Doctrine in controllers and to pass data to a view.

You can download current version of the component from here.

Why in-house frameworks are bad

Posted by Siim on August 26th, 2009

People like to think that having an in-house framework for all the projects with all available different kind of 3rd-party libraries is a good thing. Hey, you can save a bunch of time when you doesn’t have to write common code over and over again, don’t you?

Well, things aren’t so simple. Having some extras always causes some burden on the maintenance. There are plenty of reasons to prove that:

  • Framework should be developed separately from projects using it
    It adds extra overhead to update the framework, because someone must check if the proposed change fits in the framework. And after the change, projects which use the framework should also be updated. It all takes extra time which could be avoided.
  • Who is the charge of the development?
    Someone must be the charge of the framework or it ends like a /dev/null – holding bunch of stuff that nobody uses. The one should be responsible of selecting features to add or not to add.
  • Tracking framework versions
  • Projects have different requirement to fit all
    Most of the projects are still quite different by their requirements, so framework may finally contain much code which is used by the one-two separate projects only
  • It takes time to develop correct and working framework
    All takes time, so instead of creating business value, we spend time to create some internal framework which, in the end, is used only by the single project. What a waste of the resources.

I have participated in a quite a few projects where common frameworks were a hot topic and we tried to make all things so general that it would fit in the framework. But in the end we spent more time on developing the framework than creating the business value, so the projects delayed. There were times when I personally also believed that a framework is a must and tried to create a usable framework before creating some real value (also in my personal projects).

I’m not saying that all the frameworks are bad, I just think that developing your own framework may not be such a good idea. In my opinion, such frameworks should be open source, so the community can be charge of the road.


Copyright © 2007 Siim Viikman's blog.