otakoyi/sitemap

Asgardcms CMS Sitemap

dev-master 2018-09-28 14:49 UTC

This package is not auto-updated.

Last update: 2024-04-22 04:45:14 UTC


README

This package can generate a sitemaps without you having to add URLs to it manually.
In general. Sitemap does not know about installed modules and database structure. Each module should listen to the event and put into sitemap collection its data.

  • The sitemap can be run by the cron job or manually by artisan command `php artisan sitemap:generate`
  • It send event XmlSitemapBuilding . This event has SitemapCollection instance.
  • Each module should subscribe to this event and add its data.

Here an example:

Run sitemap

 \Modules\Sitemap\Console\SitemapGenerateCommand::handle
 
 
 public function handle()
 {
     $sitemaps = new SitemapCollection(); // Create collection

     event(new XmlSitemapBuilding($sitemaps)); // assign it into event

    // after modules added its data to collection, generate sitemap.xml

     $this->generate($sitemaps);
 }
 

How to subscribe module to this event:

Open your service provider and subscribe to event `\Modules\Sitemap\Events\XmlSitemapBuilding::class` in boot() method.

 if (class_exists(\Modules\Sitemap\Events\XmlSitemapBuilding::class)) {
     $this->app['events']->listen(
         \Modules\Sitemap\Events\XmlSitemapBuilding::class,
         \Modules\Catalog\Events\Handlers\RegisterSitemap::class
     );
    }

Create handler for this event `\Modules\Catalog\Events\Handlers\RegisterSitemap::class`

and add into collection your entities

<?php 
namespace Modules\Catalog\Events\Handlers;

use Modules\Catalog\Entities\CategoriesSitemap;
use Modules\Catalog\Entities\ProductsSitemap;
use Modules\Sitemap\Events\XmlSitemapBuilding;

class RegisterSitemap
{
    public function handle(XmlSitemapBuilding $collection)
    {
        $collection->add(new CategoriesSitemap()); 
        $collection->add(new ProductsSitemap());
    }
}

CategoriesSitemap should implement Modules\Sitemap\Contracts\Sitemap interface


<?php

namespace Modules\Catalog\Entities;

use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Sitemap\Contracts\Sitemap;
use Modules\Sitemap\Entities\XmlTags\Changefreq;
use Modules\Sitemap\Entities\XmlTags\Url;

class CategoriesSitemap implements Sitemap
{
    public function getItems()
    {
        $priority = 0.7;
        $res = [];

        $items = Categories::where('active', 1)->get(['id','created_at', 'updated_at']);


        $prefix = config('catalog.category.url_prefix');

        foreach (LaravelLocalization::getSupportedLocales() as $locale => $language) {
            foreach ($items as $item) {
                $loc = LaravelLocalization::localizeUrl($prefix . $item->slug);
                $lastmod = empty($item->updated_at) ? $item->created_at : $item->updated_at;
                $res[] = new Url($loc, $lastmod->toIso8601String(), Changefreq::DAILY, $priority);
            }

        }

        return $res;
    }
}