Monday, July 14, 2008

CakePHP Plugins

Plugins were a great idea added to CakePHP 1.2 that allows you to create a mini web application inside your main web application. This mini web application you can then distribute to other users, or your other projects, to reduce re-inventing the wheel so much.

Plugins were a great idea, but is not quite something the CakePHP core team really focuses much attention on, and probably never will. Despite that, CakePHP plugins can still be very useful for decreasing code time between projects - as long as you remember the pitfalls associated with them.

Some very important things to remember when working with Plugins:

  • When naming controllers, try to make their names unique (to prevent any ambiguity errors if two controllers have the same name) Usually prefixing any filename with the plugin's name works great (such as calendar_events_controller.php where calendar is the plugin name)
  • Every controller in your plugin must be told where to find its models. Even though you're using the $uses variable, still try to stick with CakePHP's conventions of having 1 model per controller. To tell your controller where your model is, use the following:
    • var $uses = array('PluginName.ModelName');
  • When working with model associations in a plugin, never use the short form (eg. $hasMany = ModelName); always extend it like the following examples(!Notice how className has PluginName.ModelName, where the ModelName before that is by itself!):


var $hasMany = array(
'ModelName' => array(
'className' => 'PluginName.ModelName',
)
);

and

var $belongsTo = array(
'ModelName' => array(
'className' => 'PluginName.ModelName',
),
);

below are two examples taken from two different models:
Special Note: The key in the array doesn't contain the plugin name but the className part does

var $hasMany = array(
'CalendarAttendantsEvent' => array(
'className' => 'Calendar.CalendarAttendantsEvent',
'dependent' => true,
)
);

var $belongsTo = array(
'CalendarAttendant' => array(
'className' => 'Calendar.CalendarAttendant',
'foreignKey' => 'calendar_attendant_id',
),
'CalendarEvent' => array(
'className' => 'Calendar.CalendarEvent',
'foreignKey' => 'calendar_event_id',
),
);


Using the above examples, I haven't had any troubles working with associated models in my plugin, but any other way I've tried wouldn't work properly in some cases (such as accessing a model's function through associations with $this->ModelName->functionName(); )

Also, please see the manual for more information: http://book.cakephp.org/view/114/plugins

1 comment:

empe said...

do you know how to validate via plugins model?

i'm developing a section of my project by creating a plugins that has its controller, model and view

but validation model from plugins doesnt work....

it alwasy return true

it stressed me out..

would you like to help me out?

please, send me an email to orangerdigiart@gmail.com