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

时间:2015-06-16 05:52:24

标签: php yii yii-url-manager

我正在应用程序中创建一个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,它会调用索引操作而不是视图。如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

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