Config.php loads before the plugin - Alternative solution?

I’ve built a very simple xml sitemap plugin. I feed it with data from config.php like this:

$sitemap = new QuerySitemap();
$sitemap->add('https://example.com');
$sitemap->add('https://example.com/contact');
$sitemap->add(array(
  'loc' => 'https://example.com/about',
  'lastmod' => '2004-11-23',
  'priority' => '0.3',
  'changefreq' => 'weekly'
));

The above does not work because config.php has not yet loaded the file with the class QuerySitemap.

This works:

include kirby()->roots()->plugins() . DS . 'kirby-query-sitemap-xml' . DS . 'class.php';

$sitemap = new QuerySitemap();
$sitemap->add('https://example.com');
$sitemap->add('https://example.com/contact');
$sitemap->add(array(
  'loc' => 'https://example.com/about',
  'lastmod' => '2004-11-23',
  'priority' => '0.3',
  'changefreq' => 'weekly'
));

But to include the file here feels wrong and seems unnecessary.

Any idea how I can get around it? Every suggestion is welcome, even very creative ones.

Update

I got it a little bit shorter, but I would prefer to skip that line completely:

kirby()->plugin('kirby-query-sitemap-xml');`

$sitemap = new QuerySitemap();
$sitemap->add('https://example.com');
$sitemap->add('https://example.com/contact');
$sitemap->add(array(
  'loc' => 'https://example.com/about',
  'lastmod' => '2004-11-23',
  'priority' => '0.3',
  'changefreq' => 'weekly'
));

Update 2

One line shorter with static class:

kirby()->plugin('kirby-query-sitemap-xml');

sitemapQuery::add('https://example.com');
sitemapQuery::add('https://example.com/contact');
sitemapQuery::add(array(
  'loc' => 'https://example.com/about',
  'lastmod' => '2004-11-23',
  'priority' => '0.3',
  'changefreq' => 'weekly'
));

But the first line still disturbs me. :confused:

why not require the static class in custom site.php. like when adding composer autoload?

Thanks for your idea.

I solved it a bit different (with a snippet solution):

Just a quick note: You should never, ever load plugins from config.php. Otherwise other plugins won’t get loaded afterwards.

I’d just use a config option for this, I don’t see any reason why the code needs to run in config.php and the options can’t be defined declaratively. And even if there is a need to run code, consider using an option with a callback.

The final solution is quite perfect and solves this problem nicely.

Thanks anyway. :slight_smile:

Yes, just wanted to leave this note here in case someone else has the same issue.

1 Like