函数调用的使用-API消息返回为例

<?php
/**
 * 调用方法原则,属于谁,就可以把谁写成一个类,然后去调用谁
 * 返回的API一般有三种,response   error   notfound
 * 每个返回都需要response  所以我们使用response类做返回
 * 返回错误消息error时,我们可以直接调用response方法
 * notfound又属于error的一种,所以可以调用error方法
 */
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ApiController extends Controller
{
    protected $statusCode = 200;

    /**
     * @return int
     */
    public function getStatusCode()
    {
        return $this->statusCode;
    }

    /**
     * @param $statusCode
     * @return $this
     */
    public function setStatusCode($statusCode)
    {
        $this->statusCode = $statusCode;
        return $this;
    }

    /**
     * @param string $message
     * @return mixed
    * not found 本身就属于404,所以在此处可以直接写成404
     */
    public function responseNoFonud($message = 'No Found')
    {
        return $this->setStatusCode(404)->responseError($message);
    }

    /**
     * @param $message
     * @return mixed
     */
    public function responseError($message)
    {
        return $this->response([
            'status'    => 'failed',
            'errors'    => [
                'status_code' => $this->getStatusCode(),
                'message'     => $message
            ]
         ]);
    }

    /**
     * @param $data
     * @return mixed
     */
    public function response($data)
    {
        return \Response::json($data,$this->getStatusCode());
    }
}

使用实例
注意事项。我们在使用中可能会需要setStatusCode()函数去设置返回的状态,形成以下的链式函数,这个时候我们需要在函数中返回这个类return $this;

class LessionController extends ApiController
{
    public function index()
    {
        return $this->setStatusCode(400)->responseError('error返回');
    }
}

responseError('error返回')
public function index()
    {
        return $this->responseNoFonud();
    }
responseNoFonud()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,099评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,956评论 25 709
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,662评论 0 17
  • 蒲公英 我要为你摘下一瓣云朵 它被天空染成了蓝色 我要为你摘下一瓣羽毛 它被乳汁哺育成白色 我要为你摘下一瓣...
    弘毅123阅读 201评论 0 1
  • 9月开始想学画画,本来只是想带着孩子一起画,培养一下孩子的兴趣,所以一开始就画一些简笔画简单涂一点颜色,看看开始时...
    彩橙子阅读 755评论 0 0