vladimiralekseev / yii2-sitemap
Yii2 sitemap module extension
Package info
github.com/vladimiralekseev/yii2-sitemap
Type:yii2-extension
pkg:composer/vladimiralekseev/yii2-sitemap
Requires
- php: >=8.2
- yiisoft/yii2: ~2.0.0
README
PHP 8.3 compatible drop-in replacement for the abandoned himiklab/yii2-sitemap-module.
Generates sitemap.xml dynamically on every HTTP request with optional response caching.
Installation
The preferred way to install this extension is through composer.
Either run
composer require vladimiralekseev/yii2-sitemap
or add
"vladimiralekseev/yii2-sitemap": "~1.0.0"
to the require section of your composer.json file.
Configuration
1. Configure Module
Add the module to your application configuration (web.php or main.php):
'modules' => [ 'sitemap' => [ 'class' => \vladimiralekseev\sitemap\Sitemap::class, 'cacheExpire' => 86400, // Duration in seconds. Use false to disable caching. 'models' => [ \(\app\models\SiteMenu::class, \app\models\TextPage::\)class, ], 'urls' => [ [ 'loc' => '/', 'changefreq' => \vladimiralekseev\sitemap\behaviors\SitemapBehavior::CHANGEFREQ_DAILY, 'priority' => 1.0 ], ], ], ],
2. Attach Behavior to Models
Each ActiveRecord class included in the models array must attach the SitemapBehavior:
use yii\db\ActiveQuery; use yii\db\ActiveRecord; use yii\helpers\Url; use vladimiralekseev\sitemap\behaviors\SitemapBehavior; public function behaviors() { return [ 'sitemap' => [ 'class' => SitemapBehavior::class, 'scope' => function (ActiveQuery \(query) {\)query->select(['url', 'lastmod']); \(query->andWhere(['is_deleted' => 0]); }, 'dataClosure' => function (ActiveRecord\)model) { return [ 'loc' => Url::to(\$model->url, true), 'lastmod' => strtotime(\$model->lastmod), 'changefreq' => SitemapBehavior::CHANGEFREQ_DAILY, 'priority' => 0.8, ]; }, ], ]; }
Routing
To make the sitemap accessible via /sitemap.xml, add the following rule to your urlManager configuration:
'components' => [ 'urlManager' => [ 'rules' => [ 'sitemap.xml' => 'sitemap/default/index', ], ], ],