How to make a REST API first web application in Laravel

后端 未结 6 1612
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-07 15:43

I want to make an API first application in Laravel. I don\'t know what is the best approach to do this, I will explain what I am trying to do, but please feel free to give a

6条回答
  •  情书的邮戳
    2020-12-07 16:21

    I would also recommend using a repository. Attempting to call one controller from another would be falling into a pattern called HMVC (Hierarchical model–view–controller). This means that your entire application relies on lower modules. In this case, your API would serve as a repository for your data (which isn't the worst thing in the world at first).

    However, when you then modify the structure of how data is returned in your API, everything else relying on it would have to know how to respond. Say you wanted to have authorization checks to see if a logged in user should be able to see the details of a returned user and there was an error.

    In the API, you would return a Response object with a 403 forbidden code and some meta data. Your HTML controller would have to know how to handle this.

    Contrast this to a repository which could throw an exception.

    public function findById ($id)
    {
        $user = User::findOrFail($id);
    
        if (Auth::user->hasAccessTo($user)) {
            return $user;
        } else {
            throw new UnauthorizedAccessException('you do not have sufficient access to this resource');
        }
    }
    

    And your API controller would look more like this:

    public function show($id)
    {
        try {
            return $this->user->findById($id);
        } catch (UnauthorizedAccessException $e) {
            $message = $e->getMessage();
            return Response::json('403', ['meta' => ['message' => $message]]));
        }
    }
    

    Your HTML controller would then look like this:

    public function show($id)
    {
        try {
            $user = $this->user->findById($id);
        } catch (UnauthorizedAccessException $e) {
            Session::flash('error', $e->getMessage());
            // Redirect wherever you would like
            return Response::redirect('/');
        }
    }
    

    This gives you very reusable code and let's you change your controller implementations independently without worry of changing the other's behavior. I wrote more on how to implement the repository pattern in this post: you can ignore the interface and skip right to the implementations if you would like.

提交回复
热议问题