How to automatically load an AppView from a plugin in cakephp?

Here I developed a nano system to publish thoughts in a diary, very simple, but functional for the need. The content is in a Json structure and there would be a need to change the aesthetics of the diary through themes. This way, I created a custom view that loads json, converts it to HTML and takes the theme chosen by the user, renders it and sends it to the browser.

Due to the possibility of having countless themes, I decided to create a directory in /src with the name themes and within it each directory is a different theme with the content being the same structure as the /templates directory in cakephp.

Everything works perfectly. But, out of necessity, to deploy it to the existing cakephp website as well, I decided to transform it into a cakephp plugin. I loaded this plugin. I configured the mysite.com/diary/ routes for this plugin. This way, the diary system works fine, until there is an error that requires me to return a personalized error page that is in the chosen theme.

Previously it worked normally, if there was any error, it would load the specific template within the /src/Themes/mytheme/Error directory of the chosen theme to display the message. But as a plugin, the directory now being /plugins/diary/src/Themes/ when an error occurs, cakephp ignores my custom view and shows errors in the /templates directory or in the core itself.

In the plugin, I load the view with:

$this->viewBuilder()->setClassName('diary.myview');

Previously, the view was AppView.php with customized rendering.

And maybe that’s the point. In the plugin I have to indicate the view, but in the main app the view is loaded automatically. And I didn’t want to change anything in the core’s default view or /src/view/AppView.php itself because there is something else running there. The idea is that everything would have to be isolated within the plugin.

I could do something in the application’s /src/controller/AppController.php:

  if($this->getPlugin() === 'Diary'){
  $this->viewBuilder()->setClassName('Diary.wThemes');
  }

This ends up working, but since I need:

$this->viewBuilder()->setTheme('morning-prayers);

To choose the theme within /plugins/diary/src/controller/AppController.php of the Diary Plugin to move to the Diary.wThemes view, the name of the theme does not appear. In Diary.wThemes the null value appears and an error appears so I can add a plugin with the name of the theme which is the natural name of cakephp, but I need to capture it within the custom render method of my Diary.wThemes.

Is there a way to load an AppView from a plugin automatically? Why doesn’t cakephp do this or provide an option to load the view at the beginning or in the routes within a plugin?

The fact is that I need to capture the name of the theme within the plugin and get it in my wThemes view, but cakephp returns an error first.

Thanks in advance.