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

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

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

1.更改配置:

'urlManager' => [

'class' => 'yii\web\UrlManager',

'enablePrettyUrl' => true,

'enableStrictParsing' => true,

'showScriptName' => false,

'rules' => [

'' => 'cms/index',

['class' => 'yii\rest\UrlRule', 'controller' => 'customer/api',

'pluralize' => false,

],

# 定义方法: public function actionSearch($name); 就是search方法传入的参数

'POST customer/api/search/' => 'customer/api/search',

//'POST customer' => 'customer/index/create',

],

],

也就是添加:

'POST customer/api/search/' => 'customer/api/search',

name代表的是参数

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

namespace myapp\frontend\code\ECM\Customer\controllers;

use yii\web\Response;

use Yii;

use yii\rest\ActiveController;

use myapp\frontend\code\ECM\User\models\Product;

class ApiController extends ActiveController

{

public $modelClass = 'myapp\frontend\code\ECM\User\models\Product';

public function behaviors()

{

$behaviors = parent::behaviors();

#定义返回格式是:JSON

$behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;

return $behaviors;

}

public function actionSearch($name){

$one = Product::findOne(['name'=>$name]);

return $one;

}

}

3. 然后访问:

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

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

HTTP/1.1 200 OK

Server: nginx

Date: Wed, 18 Nov 2015 02:26:40 GMT

Content-Type: application/json; charset=UTF-8

Transfer-Encoding: chunked

Connection: keep-alive

X-Powered-By: PHP/5.4.34

{"id":2,"name":"xxxx","description":"ddddd","image":null,"status":null,"created_at":null}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值