Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
返回的Php函数父级_Php_Oop - Fatal编程技术网

返回的Php函数父级

返回的Php函数父级,php,oop,Php,Oop,我有两个函数,它们使用这样一个验证器 public function store( Request $request ) { $validate = $this->validator( $request ); if ( $validate->fails() ) { return response()->json( [ 'errors' => $validate->errors() ] ); } } pu

我有两个函数,它们使用这样一个验证器

public function store( Request $request ) {
      $validate = $this->validator( $request );
      if ( $validate->fails() ) {
            return response()->json( [ 'errors' => $validate->errors() ] );
      }
 }

public function update( Request $request, $id ) {
      $validate = $this->validator( $request, $id );

      if ( $validate->fails() ) {
            return response()->json( [ 'errors' => $validate->errors() ] );
      }
}

private function validator( Request $request, $id = "" ) {
      $validator = Validator::make( $request->all(), [
            'name'                  => 'required',
            'email'                 => 'required|email|unique:users,email,' . $id,
            'password'              => 'required|min:6|confirmed',
            'password_confirmation' => "required",
            'role'                  => "required"
      ] );
      if ( $validate->fails() ) {
            return response()->json( [ 'errors' => $validate->errors() ] );
      }
      return $validator;
 }
在这个if验证器中,它将响应返回给验证器函数而不是父函数。
我想编写函数验证器来检查并给出父级返回响应,因为我不想一次又一次地检查和返回

您可以抛出错误,该错误将给出直接响应,现在不需要在函数中一次又一次地返回

throw new HttpResponseException(response()->json($error, 422, $headers));

我认为这将对您有所帮助。

您可以创建一个继承
请求的类,并验证其输入

在控制器端,您只有:

public function store(SomeRequestValidation $request ) {
      //Do something because it has been validated in SomeRequestValidation
 }

public function update(SomeRequestValidation $request) {
      //Do something because it has been validated in SomeRequestValidation
}
注意:如果这是Laravel,我们谈论的是FormRequests

编辑:一个覆盖请求函数的小例子

public function authorize(Request $request)
    {
        if (/*something*/) {
            return true;
        }
        return false;
    }

public function forbiddenResponse()
    {
        return json_encode("Oh no you don't");
        //return response()->view('errors.403');
    }


要创建请求,它将返回重定向到页面的错误,而不仅仅是返回json。我为APIDear@Chando写这篇文章,我编辑了我的文章,其中有一个指向文档的链接,还有一个关于如何实现你所期望的目标的示例。实际上,只要搜索文档,您就可以做任何您想做的事情。上面的示例是关于禁止响应的(当authorize为false时)。无论验证是否成功,返回的内容都可以使用相同的方法。谢谢你的否决票,小心点,我不会反对你的。谢谢你的回复和评论。