Structuring CakePHP models in subfolders

Say you want to organise your CakePHP models (tables) into subfolders. If you simply move the class into a subfolder, it won’t be picked up automatically. For example, here’s how you can tell the TableLocator to look for OrderStatuses in a specific subfolder Orders under Model/Table. In your controller: First, prepare the shorthand variables. $tableRegistry… Continue reading Structuring CakePHP models in subfolders

Setting up CakePHP CRUD plugin to use tables from another plugin

In the controller where you initialise Crud: $this->loadComponent(‘Crud.Crud’, [ // … ]); $this->Crud->useModel(sprintf( ‘%s.%s’, ‘MyPlugin’, $this->Crud->getController()->defaultTable )); Prevent linking to the plugin where your tables are: /** * Before render callback. * * @param \Cake\Event\Event $event The beforeRender event. * @return void */ public function beforeRender(\Cake\Event\EventInterface $event) { // prevent linking to the table plugin:… Continue reading Setting up CakePHP CRUD plugin to use tables from another plugin

Where to put an event listener in a plugin?

You’re creating an event listener that inserts a database record every time the matching event fires. And you need the listener to be in a plugin. Which folder do you put it in? Here it says: A good place for this might be Plugin/src/Controller/Event And @admad on CakeSF Slack says it can also be Plugin/src/Event/.… Continue reading Where to put an event listener in a plugin?

Get the current plugin name in CakePHP

If you need the current plugin name in e.g. config/routes.php or config/bootstrap.php, and don’t want to hardcode it by hand, you can use $this->getName() instead. Example: Router::plugin($this->getName(), function (RouteBuilder $routes) { $routes->fallbacks(DashedRoute::class); }); The above is effectively the same as: Router::plugin('MyPlugin', function (RouteBuilder $routes) { $routes->fallbacks(DashedRoute::class); });

CakePHP plugin: None of the currently connected routes match the provided parameters

If you want your plugin to have and use routes, you need to configure it first – otherwise, None of the currently connected routes match the provided parameters. Add a matching route to config/routes.php Start by enabling routes and bootstrapping when you load the plugin in your src/Application.php: $this->addPlugin(‘MyPlugin’, [‘bootstrap’ => true, ‘routes’ => true]);… Continue reading CakePHP plugin: None of the currently connected routes match the provided parameters