Chapter 13. Plugins

Table of Contents

13.1. Creating a Plugin
13.2. Plugin Controllers
13.3. Plugin Models
13.4. Plugin Views
13.5. Working With Plugins

CakePHP allows you to set up a combination of controllers, models, and views and release them as a packaged application plugin that others can use in their CakePHP applications. Have a sweet user management module, simple blog, or web services module in one of your applications? Package it as a CakePHP plugin so you can pop it into other applications.

The main tie between a plugin and the application it has been installed into is the application's configuration (database connection, etc.). Otherwise, it operates in its own little space, behaving much like it would if it were an application on it's own.

13.1. Creating a Plugin

As a working example, let's create a new plugin that orders pizza for you. What could be more useful in any CakePHP application? To start out, we'll need to place our plugin files inside the /app/plugins folder. The name of the parent folder for all the plugin files is important, and will be used in many places, so pick wisely. For this plugin, let's use the name 'pizza'. This is how the setup will eventually look:

Example 13.1. Pizza Ordering Filesystem Layout

/app
    /plugins
        /pizza
            /controllers                <- plugin controllers go here
            /models                     <- plugin models go here
            /views                      <- plugin views go here
            /pizza_app_controller.php   <- plugin's AppController, named after the plugin
            /pizza_app_model.php        <- plugin's AppModel, named after the plugin

While defining an AppController and AppModel for any normal application is not required, defining them for plugins is. You'll need to create them before your plugin works. These two special classes are named after the plugin, and extend the parent application's AppController and AppModel. Here's what they should look like:

Example 13.2. Pizza Plugin AppController: /app/plugins/pizza_app_controller.php

<?php

class PizzaAppController extends AppController
{
    //...
}

?>

Example 13.3. Pizza Plugin AppModel: /app/plugins/pizza_app_model.php

<?php

class PizzaAppModel extends AppModel
{
    //...
}

?>

If you forget to define these special classes, CakePHP will hand you "Missing Controller" errors until the problem is rectified.