PHP code example of prokhonenkov / yii2-sitemap-generator

1. Go to this page and download the library: Download prokhonenkov/yii2-sitemap-generator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

prokhonenkov / yii2-sitemap-generator example snippets




return [
    // ... your config
    'components' => [
        'sitemap' => [
            'class' => \prokhonenkov\sitemapgenerator\SitemapGenerator::class, // The class which implements SitemapSourceInterface, SitemapItemInterface
            'baseUrl' => 'https://sitename.com',
            'sitemapPath' => '@webroot',
            'models' => [
                \app\models\PostsSitemap::class,
                \app\models\ProductsSitemap::class,
            ],
            'languages' => [
                'ru-RU',
                'en-US',
                'kk-KZ',
            ],
        ]
    ]
];




use app\modules\posts\models\Posts;
use prokhonenkov\sitemapgenerator\interfaces\SitemapItemInterface;
use prokhonenkov\sitemapgenerator\interfaces\SitemapSourceInterface;
use samdark\sitemap\Sitemap;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;

class PostsSitemap extends Posts implements SitemapSourceInterface, SitemapItemInterface
{
	public function getSitemapItems(): array
	{
		return ArrayHelper::merge([new PostsSitemapItem()], self::find()->all());
	}

	public function getSitemapName(): string
	{
		return 'posts';
	}

	public function getLastModified(): int
	{
		return strtotime($this->updated_at);
	}

	public function getLocation($index = null): string
	{
		return Url::to(['/posts/view', 'id' => $this->id], true);
	}

	public function getChangeFrequency(): string
	{
		return Sitemap::MONTHLY;
	}

	public function getPriority(): string
	{
		return 0.5;
	}
}




use app\modules\posts\models\Posts;
use prokhonenkov\sitemapgenerator\interfaces\SitemapItemInterface;
use samdark\sitemap\Sitemap;
use yii\helpers\Url;

class PostsSitemapItem extends Posts implements SitemapItemInterface
{
	public function getLastModified(): int
	{
		return strtotime( Posts::find()
			->max('updated_at'));
	}

	public function getLocation($language = null): string
	{
		\Yii::$app->language = $language;
		return Url::to(['/posts/index'], true);
	}

	public function getPriority(): string
	{
		return 1;
	}

	public function getChangeFrequency(): string
	{
		return Sitemap::DAILY;
	}
}


public function afterSave($insert, $changedAttributes)
{
    parent::afterSave($insert, $changedAttributes);
    \Yii::$app->sitemap->generate();
}

php composer.phar