| 13/03/2013, 11:00 RedBean Models with Composer
I've finally got to the point where I want to use custom model classes with the RedBean ORM. I personally think this sure speaks volumes for the technology after already using it for various projects for around a year because, as a result, it's reconfirming it's ability to provide 'schemaless' development compared to other ORM technologies. (See DBIx::Class, Doctrine, ActiveRecord etc). Being a Composer convert I automatically wanted to have my models residing in a 'namespaced location' inside my (Empathy) web apps so that they could be auto loaded for me. Although I appreciate the RedBean creator's views on namespaces in PHP, because I think less is often more, I've simply always been a fan, especially since I started to use Composer and becoming aware of the PSR 0 autoloading standard. So assuming I have some 'Acme' components in my web app I would declare them according to the composer documentation as such:
{
"autoload": {
"psr-0": {"Acme": "src/"}
}
}
I could then have my models stored in 'src/Acme/Models' but how would RedBean and specifically the event listener that belongs to FUSE know about them? I needed to follow the howto on the RedBean wiki for creating a model 'formatter' class. This class (that resides in the same location) would then be loaded and registered with RedBean in my application controller superclass as such:
require('ModelFormatter.php');
\RedBean_ModelHelper::setModelFormatter(new \ModelFormatter());
And the contents of this class:
class ModelFormatter implements RedBean_IModelFormatter
{
public function formatModel($model)
{
$model = '\\Acme\\Models\\Model'.ucfirst($model);
return $model;
}
}
The model classes themselves would then look like this:
namespace Acme\Models;
class ModelFoo extends \RedBean_SimpleModel
{
public function dispense()
{
//echo "I'm a shiny new bean with a namespaced model class!";
}
}