Yii2其余网址路由

时间:2015-05-18 09:36:47

标签: php rest yii yii2

我在Yii2中调用其余api的url时遇到问题。我想打个网址:

http://localhost/index-dev.php/myapi/collection/18

其中18是Id。

在我的web.php配置中,我有以下代码,以及其他程序员的其他设置:

'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => true,
        'rules' => [
            ['class' => 'yii\rest\UrlRule', 'controller' => ['coding/nodes', 'coding/scales','myapi/collection']],                
            '<controller:\w+>/<id:\d+>' => '<controller>/view',
        ],            
    ],

当我拨打我的网址时,我得到了

未找到(#404)

我做错了什么?

3 个答案:

答案 0 :(得分:5)

我有同样的问题,你可以禁用prural

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => true,
    'rules' => [
        ['class' => 'yii\rest\UrlRule', 'controller' => ['coding/nodes', 'coding/scales','myapi/collection']],                
        '<controller:\w+>/<id:\d+>' => '<controller>/view',
        'pluralize' => false,
    ],            
],

答案 1 :(得分:4)

您需要在URL中使用复数的模型类名来访问单个模型:

http://localhost/index-dev.php/myapi/collections/18

查看documentation of yii\rest\UrlRule

  

上面的代码将创建一整套支持以下RESTful API端点的URL规则:

     
      
  • &#39; PUT,PATCH用户/&lt; id&gt;&#39; =&GT; &#39;用户/更新&#39;:更新用户
  •   
  • &#39;删除用户/&lt; id&gt;&#39; =&GT; &#39;用户/删除&#39;:删除用户
  •   
  • &#39; GET,HEAD用户/&lt; id&gt;&#39; =&GT; &#39; user / view&#39;:返回用户的详细信息/概述/选项
  •   
  • &#39; POST用户&#39; =&GT; &#39; user / create&#39;:创建新用户
  •   
  • &#39; GET,HEAD用户&#39; =&GT; &#39; user / index&#39;:返回用户的列表/概述/选项
  •   
  • &#39;用户/&LT; ID&GT;&#39; =&GT; &#39; user / options&#39;:处理用户的所有未处理动词
  •   
  • &#39;用户&#39; =&GT; &#39; user / options&#39;:处理所有未处理的用户集合动词
  •   

答案 2 :(得分:3)

我建议为API创建单独的模块 并将您的UrlManager配置为...... :)

'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                [
                    'class' => 'yii\rest\UrlRule', 
                    'pluralize'=>false,
                    'controller' => ['v1/country','v1/user'],
                    'tokens' => [
                        '{id}' => '<id:\\w+>'
                    ],
                    'extraPatterns' => [
                        'POST register' => 'register', //from url 
                        'GET exists'=>'exists',
                        'POST login'=>'login',
                        'POST follow'=>'follow',
                        'POST category'=>'category',
                        'PUT profile'=>'profile',
                        'PUT change_password'=>'change_password',
                        'PUT feed_interested'=>'feed_interested',
                    ],


                ]
            ],        
        ]

更多细节@ Create Rest Api