In Yii2, it is supported to generate an alias-based link, which can only contain lowercase letters, numbers, middle underscores, @ and underscores.
1. The table structure is designed to allow alias to be null, and the default is null, and a unique index is added.
-- `official-website-management-system`.articles definition
CREATE TABLE `articles` (
`id` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
`alias` varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `idx-alias` (`alias`),
KEY `idx-category_id` (`category_id`),
KEY `idx-status` (`status`),
KEY `idx-updated_at` (`updated_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
2. When the background form is submitted for editing, the empty string is automatically converted to null. Set conversion rules and validation in the Rules of the model
/**
* {@inheritdoc}
*/
public function rules()
{
return [
['alias', 'filter', 'filter' => function ($value) {
return $value === '' ? null : $value;
}],
['alias', 'match', 'pattern' => '/^[a-z0-9\-@_]+$/', 'message' => '别名只能包含小写字母、数字、中划线、@ 和下划线。'],
];
}
3. In the front-end view file, the realization of the link is as follows
frontend/views/article/index.php
<a class="item" href="<?= ArticleUrlHelper::detailUrl($article) ?>">
frontend/helpers/articleurlhelper.php
public static function detailUrl($article): string
{
if (!empty($article['alias']) && UrlHelper::isValidAlias($article['alias'])) {
return Url::to(['article/view', 'alias' => $article['alias']]);
}
return Url::to(['article/view', 'id' => $article['id']]);
}
frontend/helpers/urlhelper.php
public static function isValidAlias(string $alias): bool
{
return preg_match('/^[a-z0-9\-@_]+$/', $alias) === 1;
}
4. Configure urlmanager in frontend/config/main.php as follows
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => true,
'normalizer' => [
'class' => yii\web\UrlNormalizer::class,
'collapseSlashes' => true,
'normalizeTrailingSlash' => true,
],
'rules' => [
'' => 'page/index',
// 资讯详情
'industry/detail-.html' => 'article/view',
'industry/.html' => 'article/view',
],
],
5. When the alias: @dd87-_s, the generated link is: /industry/%40dd87-_s.html . as shown in Figure 1
6. The reason is that url::to() automatically encodes the parameters, alias is @dd87-_s, where @ is a special character, which will be encoded as %40. Decided not to deal with it for the time being.
