简体   繁体   English

Laravel:将REST控制器与普通控制器和视图结合在一起吗?

[英]Laravel: Combine REST-Controllers with normal controllers and views?

I want to create an new app and for this purpose I've chosen laravel. 我想创建一个新的应用程序,为此,我选择了laravel。 So I'm also new to laravel. 所以我也是Laravel的新手。

I want to integrate an API from the beginning for things like browser addons or mobile apps. 我想从一开始就为浏览器插件或移动应用程序集成API。 Of course I don't want to make it an API only app. 当然,我不想使其成为仅API的应用。 I'll still need normal views and controllers which will handle this. 我仍然需要正常的视图和控制器来处理此问题。 Now I'm a bit confused about the proper structure. 现在,我对正确的结构有些困惑。 It should output the data as JSON when it's an API request, otherwise as a normal view. 当它是API请求时,它应该将数据输出为JSON,否则作为普通视图输出。

What would be the best way to achieve this? 实现这一目标的最佳方法是什么? All tutorials are based on API only apps which doesn't help me. 所有教程均基于仅API应用程序,但对我无济于事。

Is it good practice to make UserController.php and ApiUserController.php? 制作UserController.php和ApiUserController.php是一个好习惯吗? Or UserController.php and a subfolder structure like API/v1.0/UserController.php? 还是UserController.php和子文件夹结构(如API / v1.0 / UserController.php)? Wouldn't I repeat things often with this kind of structure? 我不会经常用这种结构重复一遍吗? I mean often the only thing changes is the output, isn't it? 我的意思是,通常唯一的变化就是输出,不是吗?

Thanks in advance! 提前致谢!

Your API should be served on API routes, those can be in the same controller as the other user stuff but they really don't have to be. 您的API应该在API路由上提供,这些路由可以与其他用户的资源位于同一控制器中,但实际上并非必须如此。

I like to use an ApiController with all the API functions in it. 我喜欢将ApiController与所有API函数一起使用。 In that you can implement stuff like "showUsers" and have it return User::all() or User::paginate(50). 这样,您可以实现“ showUsers”之类的东西,并使其返回User :: all()或User :: paginate(50)。 If you directly return a Model in Laravel it will output as JSON by default, which is pretty convenient. 如果您直接在Laravel中返回模型,则默认情况下它将以JSON输出,这非常方便。

Now for some real API goodness, I love using the API package by dingo in combination with artdarek's Laravel OAuth 2 wrapper. 现在,为了获得一些真正的API优势,我喜欢将dingo的API包与artdarek的Laravel OAuth 2包装器结合使用。 It providers really high quality secure API with lots of functionality, like rate limiting and scopes and all that cool stuff. 它提供了具有许多功能的真正高质量的安全API,例如速率限制和范围以及所有很酷的东西。

You really don't want to use RESTful controllers for an API, since you probably want differently named endpoints. 您确实不想为API使用RESTful控制器,因为您可能希望使用其他名称的终结点。 I like to keep all users at api/users but single users at user/USER for example. 我想将所有用户都保留为api / users,但将单个用户保留为user / USER。 It's just what I prefer, my API should be totally customizable and routable in my opinion. 这就是我的偏爱,我认为我的API应该是完全可定制和可路由的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM