Yii 1:UrlManager 没有在模块控制器中调用正确的操作

Yii 1: UrlManager does not call the correct action in module controller

我正在应用程序中创建一个 API 模块,我必须在 urlManager 中设置一些规则,但是当我设置一个规则并测试它是否有效时,它会调用索引操作而不是所需的操作。

在控制器中

<?php     
Class ProjectsController extends Controller
{
    // Do nothing on this request
    public function actionIndex()
    {
        // this is being echoed even if this action is not being requested
        echo 'test';
    }

    /*
    *   Retrieve all projects
    */
    public function actionAll()
    {
        $projects = Project::model()->findAllApi();

        echo CJSON::encode($projects);
    }

    public function actionView($id)
    {
        echo 'asd';
    }
}

config/main.php

中的 urlManager
'urlManager'=>array(
            'urlFormat'=>'path',
            'showScriptName'=>false,
            'urlSuffix'=>'.php',
            'rules'=>array(
                '<module:\w+>/<controller:\w+>/<id:\d+>'=>'<module>/<controller>/view',
                '<controller:\w+>/<id:\d+>'=>'<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
                '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
            ),
        ),

ApiModule.php

<?php

class ApiModule extends CWebModule
{
    public function init()
    {
        // this method is called when the module is being created
        // you may place code here to customize the module or the application

        // import the module-level models and components
        $this->setImport(array(
            'api.models.*',
            'api.components.*',
        ));
    }

    public function beforeControllerAction($controller, $action)
    {
        if(parent::beforeControllerAction($controller, $action))
        {
            // this method is called before any module controller action is performed
            // you may place customized code here
            return true;
        }
        else
            return false;
    }
}

所以如果我请求 http://localhost/<application>/api/projects/2 它会调用索引操作而不是视图。如何解决这个问题?

您的代码中的所有内容都是正确的。我没有在您的代码中发现任何错误!但是尝试删除 '<module:\w+>/<controller:\w+>/<id:\d+>'=>'<module>/<controller>/view' 规则并替换 api/projects/<id:\d+> => api/projects/view。这可能会有所帮助。