mrssoft/yii2-sitemap

Yii2 sitemap extension

Installs: 10 843

Dependents: 2

Suggesters: 0

Security: 0

Stars: 11

Watchers: 5

Forks: 3

Open Issues: 2

Type:yii2-extension

2.0.0 2021-09-28 09:09 UTC

This package is auto-updated.

Last update: 2024-11-28 16:05:47 UTC


README

Latest Stable Version PHP Github Total Downloads

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require mrssoft/yii2-sitemap "^2.0"

or add

"mrssoft/yii2-sitemap": "^2.0"

to the require section of your composer.json.

Usage

Create controller SitemapController.php

<?php

namespace app\controllers;

use \mrssoft\sitemap\Sitemap;

class SitemapController extends \mrssoft\sitemap\SitemapController
{
    /**
     * @var int Cache duration, set null to disabled
     */
    protected $cacheDuration = 43200; // default 12 hour

    /**
     * @var string Cache filename
     */
    protected $cacheFilename = 'sitemap.xml';
    
    protected $enablePriority = false;

    protected $enableChangeFreq = false;    

    public function models(): array
    {
        return [
            [
                'class' => \app\models\Page::class,
                'change' => Sitemap::MONTHLY,
                'priority' => 0.8,
                'lastmod' => 'updated_at',
            ]
        ];
    }

    public function urls(): array
    {
        return [
            [
                'url' => ['about/index'],
                'priority' => 0.8
            ]
        ];
    }
}

Add to your models interface \mrssoft\sitemap\SitemapInterface

<?php
namespace app\models;

class Page extends \yii\db\ActiveRecord implements \mrssoft\sitemap\SitemapInterface
{
    ...
    
    /**
     * @return \yii\db\ActiveQuery
     */        
    public static function sitemap(): \yii\db\ActiveQuery
    {
        return self::find()->where(['public' => 1]);
    }

    /**
     * @return string
     */
    public function getSitemapUrl(): string
    {
        return \yii\helpers\Url::toRoute(['page/view', 'url' => $this->url], true);
    }    
}

Add to config url rule.

'components' => [
    'urlManager' => [
        'rules' => [
            ...
            [
                'pattern' => 'sitemap', 
                'route' => 'sitemap/index', 
                'suffix' => '.xml'
            ],
            ...
        ]
    ],