yii2 RESTful 接口 api -2 : 自定义函数

时间:2022-09-16 19:34:36

yii2 的 restful 接口的默认  是帮写了很多的方法

下面我们需要书写自己的接口方法,譬如搜索方法。

1.更改配置:

  1. 'urlManager' =>[
  2. 'class' => 'yii\web\UrlManager',
  3. 'enablePrettyUrl' => true,
  4. 'enableStrictParsing' => true,
  5. 'showScriptName' => false,
  6. 'rules' => [
  7. '' => 'cms/index',
  8. ['class' => 'yii\rest\UrlRule','controller' =>'customer/api',
  9. 'pluralize' => false,
  10. ],
  11. # 定义方法: public function actionSearch($name); <name> 就是search方法传入的参数
  12. 'POST customer/api/search/<name>' => 'customer/api/search',
  13. //'POST customer' => 'customer/index/create',
  14. ],
  15. ],

也就是添加:

  1. 'POST customer/api/search/<name>' =>'customer/api/search',

 

name代表的是参数

2.我们需要返回的是json格式:

  1. <?php
  2. namespace myapp\frontend\code\ECM\Customer\controllers;
  3. use yii\web\Response;
  4. use Yii;
  5. use yii\rest\ActiveController;
  6. use myapp\frontend\code\ECM\User\models\Product;
  7. class ApiController extends ActiveController
  8. {
  9. public $modelClass ='myapp\frontend\code\ECM\User\models\Product';
  10. public functionbehaviors()
  11. {
  12. $behaviors = parent::behaviors();
  13. #定义返回格式是:JSON
  14. $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
  15. return $behaviors;
  16. }
  17. public functionactionSearch($name){
  18. $one = Product::findOne(['name'=>$name]);
  19. return $one;
  20. }
  21. }

3. 然后访问:

  1. curl -i -H"Accept:application/json" -H"Content-Type:application/json" -XPOST "http://10.10.10.252:800/customer/api/search/xxxx"

我们发现 name 为xxxx的条目被打印出来了

  1. HTTP/1.1200 OK
  2. Server: nginx
  3. Date: Wed,18 Nov201502:26:40 GMT
  4. Content-Type: application/json; charset=UTF-8
  5. Transfer-Encoding: chunked
  6. Connection: keep-alive
  7. X-Powered-By: PHP/5.4.34
  8. {"id":2,"name":"xxxx","description":"ddddd","image":null,"status":null,"created_at":null}

 

1、在'components'中加入
   'urlManager'=>array(
       'urlFormat'=>'path',                 //使用pathinfo模式,不需要?r=
       'showScriptName'=>false,             //隐藏index.php
       'rules'=>array(                      //这里面写规则,下文再做解释
           'pattern1'=>'route1',
           'pattern2'=>'route2',
           'pattern3'=>'route3',
       ),
   ),

2、在nginx中配置
找到相应站点的配置文件,nginx.conf,但如果你是lnmp,它会自动调用conf里的站点配置文件,你可在/usr/local/nginx/conf/vhost 中找到。
添加以下规则:(fastcgi_pass视具体服务器配置而定,不必更改。若规则已存在,加入红色两行)
    location ~ .*\.(php|php5)?$ {
        fastcgi_pass  unix:/tmp/php-cgi.sock;
        fastcgi_index index.php;
        include fcgi.conf;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_script_name;

    }

若你在1中配置urlmanager为不显示index.php,则还需要添加如下规则:
    location / {
        if (!-e $request_filename){
            rewrite ^/(.*) /index.php last;
        }
    }

    # if(!-e $request_filename)的意义是先确定访问地址是否是真实存在的文件,否不是,则 rewrite 至 index.php


3、在apache中配置

在根目录下建立 .htaccess 文件,添加以下代码并保存

    Options +FollowSymLinks
    IndexIgnore */*
    RewriteEngine on

    # if a directory or a file exists, use it directly
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # otherwise forward it to index.php
    RewriteRule . index.php

 

4、urlmanager的 rules 规则

   格式:'key'=>'value',

   key是用于匹配的正则表达式,value是动作及参数,

   例:

   'manage' => 'content/index',

   'manage/<controller:\w+>' => '<controller>',

   'manage/<controller:\w+>/<action:(update|delete|view)>/<id:\d+>' => '<controller>/<action>',

   'manage/<controller:\w+>/<action:(create|update|delete|admin|view|changepswd|empty)>' => '<controller>/<action>',

 

参考:

http://koda.iteye.com/blog/1128247

http://www.yiiframework.com/forum/index.php?/topic/7956-urlmanager-and-godaddy-trouble/