PHP code example of bug32 / yii2-static-url

1. Go to this page and download the library: Download bug32/yii2-static-url 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/ */

    

bug32 / yii2-static-url example snippets


// frontend/config/main.php или backend/config/main.php
return [
    'bootstrap' => [
        'staticUrl' => [
            'class' => 'bug32\\staticUrl\\StaticUrlExtension',
        ],
    ],
    // ... остальной конфиг
];

// backend/config/main.php
return [
    'modules' => [
        'static-url' => [
            'class' => 'bug32\\staticUrl\\StaticUrlExtension',
        ],
    ],
    // ... остальной конфиг
];

// extensions/static-url/src/config.php
return [
    'components' => [
        'staticUrlRule' => [
            'class' => 'bug32\\staticUrl\\components\\StaticUrlRule',
            // 'cacheEnabled' => true,           // Включить/выключить кэширование
            // 'cacheDuration' => 3600,          // Время жизни кэша в секундах
            // 'autoClearCache' => true,         // Автоочистка кэша при изменениях
        ],
    ],
    'modules' => [
        'static-url' => [
            'class' => 'bug32\\staticUrl\\StaticUrlExtension',
            // 'adminRoute' => 'static-url/backend',
            // 'enableConsoleCommands' => true,  // Включить консольные команды
            // 'enableAdminInterface' => true,   // Включить админку
            // 'defaultStatus' => 10,            // Статус по умолчанию для новых URL
            // 'urlValidationPattern' => '/^[a-z0-9\-_\/]+$/',
        ],
    ],
];

// environments/prod/common/config/main.php
return [
    'bootstrap' => [
        'staticUrl' => [
            'class' => 'bug32\\staticUrl\\StaticUrlExtension',
            'enableAdminInterface' => false, // Отключить админку в проде
            'cacheEnabled' => true,
            'cacheDuration' => 7200, // 2 часа
        ],
    ],
];

// environments/dev/common/config/main.php
return [
    'bootstrap' => [
        'staticUrl' => [
            'class' => 'bug32\\staticUrl\\StaticUrlExtension',
            'enableAdminInterface' => true,
            'cacheEnabled' => false, // Отключить кэш для разработки
            'autoClearCache' => true,
        ],
    ],
];

// console/config/main.php
return [
    'bootstrap' => [
        'staticUrl' => [
            'class' => 'bug32\\staticUrl\\StaticUrlExtension',
            'enableConsoleCommands' => true,
            'enableAdminInterface' => false,
        ],
    ],
];

// frontend/config/main.php
return [
    'components' => [
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
                // Статические URL будут добавлены автоматически в начало
                // Остальные правила остаются без изменений
                'posts/<id:\d+>' => 'posts/view',
                'ships/<slug>' => 'ship/view',
            ],
        ],
    ],
];

use bug32\staticUrl\helpers\StaticUrlHelper;

// Создать статический URL
$url = StaticUrlHelper::to('site/about'); // Вернет 'about-us'
$url = StaticUrlHelper::to('site/contact'); // Вернет 'contact'

// Создать абсолютный URL
$absoluteUrl = StaticUrlHelper::toAbsolute('site/about');

// Проверить, является ли URL статическим
if (StaticUrlHelper::isStaticUrl('about-us')) {
    echo 'Это статический URL';
}

// Получить маршрут по статическому URL
$route = StaticUrlHelper::getRouteForUrl('about-us'); // Вернет 'site/about'

// Запись в базе
url: 'about-us'
controller: 'site'
action: 'about'
params: '{}'

// Использование
StaticUrlHelper::to('site/about'); // Вернет 'about-us'

// Запись в базе
url: 'post/123'
controller: 'posts'
action: 'view'
params: '{"id": 123}'

// Использование
StaticUrlHelper::to('posts/view', ['id' => 123]); // Вернет 'post/123'

// Запись в базе
url: 'post/123'
controller: 'posts'
action: 'view'
params: '{"id": 123}'

// Использование
StaticUrlHelper::to('posts/view', ['id' => 123, 'tab' => 'details']); 
// Вернет 'post/123?tab=details'
bash
php yii migrate --migrationPath=@vendor/bug32/yii2-static-url/migrations
bash
# Список всех статических URL
php yii static-url/index

# Очистить кэш
php yii static-url/clear-cache

# Создать статический URL
php yii static-url/create "about-us" "site" "about" "{}"

# Удалить статический URL
php yii static-url/delete 1