Search code examples
cakephppluginscakephp-3.0cakephp-3.1cakephp-3.x

Can't create simple CakePHP plugin


I would like to create a plugin for CakePHP 3.1.4. The documentation is straight forward, but the example doesn't work (http://book.cakephp.org/3.0/en/plugins.html#creating-your-own-plugins)

The steps are:

composer create-project --prefer-dist cakephp/app sampleapp

Create the database. Connect to the database. Create a table "contacts". Navigate in the directory and run:

bin/cake bake plugin ContactManager

Create the controller:

bin/cake bake controller --plugin ContactManager Contacts

Re-generate the autoloader:

composer dumpautoload

Add this line to the /config/bootstrap.php file:

Plugin::load('ContactManager', ['routes' => true]);

But now, the documentation sais

"If you want to access what we’ve got going thus far, visit /contact-manager/contacts. You should get a “Missing Model” error because we don’t have a Contact model defined yet."

But this doesn't work. Instead I get an error:

Missing Controller. Cake\Routing\Exception\MissingControllerException. Cake\Routing\Dispatcher->dispatch ROOT/webroot/index.php, line 37 Error: ContactManagerController could not be found. Error: Create the class ContactManagerController below in file: src/Controller/ContactManagerController.php

This means the plugin could not be loaded otherwise it would not suggest this. When opening the DebugKit under "Include" the plugin is not in the plugins array.

I checked the composer.json files and in both the plugin is listed correctly. The bake command ran through without errors. I tried the above steps with multiple new projects with different names.

What is the problem here? Thank you very much.


Solution

  • Finally, I found the solution.

    What the docs say should be in /plugins/ContactManager/config/routes.php AND what bake plugin creates:

    Router::plugin('ContactManager', function ($routes) {
        $routes->fallbacks('DashedRoute');
    });
    

    But what really needs to be in the file instead of the above snippet is:

    Router::scope('/contactmanager', ['plugin' => 'ContactManager'], function ($routes) {
        $routes->fallbacks();
    });