yii2 RESTful 接口 api -2 : 写自己的接口方法search
链接:yii2 RESTful 接口 api -2 : 自定义函数
yii2 的 restful 接口的默认 是帮写了很多的方法
下面我们需要书写自己的接口方法,譬如查找name是xxxx的条目
1.
更改配置:
"urlManager" => [ "class" => "yiiwebUrlManager", "enablePrettyUrl" => true, "enableStrictParsing" => true, "showScriptName" => false, "rules" => [ "" => "cms/index", ["class" => "yii estUrlRule", "controller" => "customer/api", "pluralize" => false, ], # 定义方法: public function actionSearch($name); <name> 就是search方法传入的参数 "POST customer/api/search/<name>" => "customer/api/search", //"POST customer" => "customer/index/create", ], ],
也就是添加:
"POST customer/api/search/<name>" => "customer/api/search",
name代表的是参数
2.我们需要返回的是json格式:
<?php
namespace myappfrontendcodeECMCustomercontrollers;
use yiiwebResponse;
use Yii;
use yii
estActiveController;
use myappfrontendcodeECMUsermodelsProduct;
class ApiController extends ActiveController
{
public $modelClass = "myappfrontendcodeECMUsermodelsProduct";
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}声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
