沃梦达 / 编程问答 / php问题 / 正文

使用 CamelCase 操作名称时的 Yii2 路由

Yii2 routing when using CamelCase action names(使用 CamelCase 操作名称时的 Yii2 路由)

本文介绍了使用 CamelCase 操作名称时的 Yii2 路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你说下面的控制器结构

If you have say the following controller structure

<?php
namespace appcontrollers;

use Yii;
use yiiwebController;
/**
 * Test controller
 */
class TestController extends Controller
{
    public function actionMyaction(){
       ...
       //action logic
    }

    public function actionMyAction(){
       ... 
      //action logic
    }
}

可以使用路径example.com/test/myaction

每个 Yii 1.x 逻辑的第二个路由应该可以从路径 example.com/test/myAction 访问Yii2.x 中的路由使用连字符结构,只能从 example.com/test/my-action

The second route per Yii 1.x logic should be accessible from the path example.com/test/myAction in Yii2.x routing is using hyphenated structure and is accessible only from example.com/test/my-action

有没有办法在 Yii2 中使用驼峰式结构启用路由,最好不要扩展路由类?

Is there anyway to enable routing using camelCase structure in Yii2 preferably without extending with routing classes ?

这很重要,因为它破坏了所有链接(当然是整个互联网上的)向后兼容性,因此即使代码完全重写,Yii1.x 应用程序也永远无法迁移到 Yii2.x.这种变化的原因是什么?

This is important as it breaks all link ( which are of course all over the internet) backward compatibility and thus Yii1.x app can never be migrated to Yii2.x even if the code is fully rewritten. What was the reason for this change?

推荐答案

我也对这个变化有点不满,但最终我发现它使 URL 更易于阅读.我不确定在 Yii1 中是否有区分大小写的路由,在 Yii2 中我不再有这个问题(或有问题的印象).

I was thrown a little about this change too, but eventually I found it makes the URL easier to read. I was unsure about having a case sensitive route in Yii1, in Yii2 I do not have this problem (or impression of a problem) anymore.

我不确定确切的原因,但我可以告诉你,对于 SEO,最好使用 - 分隔词而不是 1 个大词.

I am not sure about the exact reason, but I can tell you that for SEO it is better to have - separating words instead of having 1 big word.

当我在 yii2 中重写一个应用程序时,我将所有需要维护的旧路由放入 url 管理器.

When I rewrote an application in yii2, I put in the url manager all the old routes that i need to maintain.

        'urlManager' => [
            'class' => 'yiiwebUrlManager',
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
.................................................
                'site/registerInterest' => 'site/register-interest',
.................................................

            ],
        ],

所以我的旧链接现在可以正常工作了.如果你想从旧路由到新路由,你也可以在 .htaccess 中放置一个 301 重定向,以保持 SEO 的活力.

So my old links work now just fine. You can also put a 301 redirect in .htaccess if you want from the old routes to the new ones to keep the SEO juice.

这篇关于使用 CamelCase 操作名称时的 Yii2 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 CamelCase 操作名称时的 Yii2 路由

基础教程推荐