CakePHP is arguably the best PHP framework with tons of features and automagics that will blow your mind. Even the best has some issues as well. I came up with an issue that is worth documenting.
Many of the sites that I create have the same Administrator backend theme. So to make things easier on me, I decided to create this theme as a private repository that I could share among my websites. This way, when it is time to add new features or fix issues, these changes and additions can be applied to all my websites by simply running `composer update`. In the process of creating this plugin and because there are labels in various template files, I decided to create a Helper that can be housed within the plugin and used by its files. All beautifully tough out until...
After I created the Helper, I could not get it to run no matter what I did. I tried all kind of CakePHP tricks that I have learned over the years, but none worked. All I was coming up with was a Missing Helper Exception. If I loaded the Helper with the App's AppView.php file then everything would run, but that was not what I wanted. After some more debugging, it comes to find out CakePHP does not touch the `app/plugins/AdminTheme/src/View/AppView.php` file that I created. I still do not know the reasoning behind this, but if a plugin is technically an application running on its own, why is this the case?
Anyway, after researching and getting some tips from a developer (@hmic) on Slack, this is the solution I came up with.
<?php
// app/config/bootstrap.php
/**
How to load a Plugin's Helper within the Plugin itself without loading the helper from within the App.
*/
use Cake\Event\EventManager;
EventManager::instance()->on('Controller.beforeRender', function($event) {
$event->subject()->viewBuilder()->helpers(['AdministratorTheme.Label']);
});
In short, this snippet of code listen to the application's beforeRender event and injects the LabelHelper. This helped solve one of CakePHP's shortcomings (or not) and works beautifully for me.