您的位置 首页 php

3分钟短文:有面子!Laravel教你简单写出专业的API

引言

在我们连接了数据库,并且使用迁移功能创建了数据库表结构, 使用Seeder为数据库初步填充了一些伪数据。有了这些准备工作,我们可以考虑做一个资源接口功能, 对外提供数据支持了。

3分钟短文:有面子!Laravel教你简单写出专业的API

代码时间

有没有感觉自己设计的 API 接口和数据跟别的大厂提供的文档数据结构不太一样, 看上去不是那么专业,或者说不是那么标准?我们和大厂还差几个年级?

Laravel 提供了简单的标准方式,可以让我们遵循最佳实践写出专业的url。 比如对于资源,使用 restful 风格声明一下的url路由地址:

3分钟短文:有面子!Laravel教你简单写出专业的API

第一列是http请求方法,第二列是laravel内声明的路由规则,第三列是对应的控制器方法。上面的资源列表,涵盖了增删改查的所有动作,可以说很全面了。

如何快捷地生成上述控制器方法呢?使用laravel脚手架指令,在命令行运行:

 php artisan make:controller EventsController --resource  

我们使用 –resource 选项,会在目标控制器内生成上述的所有方法。

生成的文件位于 app/Http/Controllers/EventsController.php 内,初始化的内容如下:

3分钟短文:有面子!Laravel教你简单写出专业的API

这些方法真的是开箱即用啊。

那么,我们还要手动一条一条地声明上面的那些路由条目吗?那真是噩梦啊。还好,laravel帮我们做好了,只用 Route 类的 resource 方法注册资源就可以了:

 Route::resource('events', 'EventsController');  

使用资源路由方法,只用指定路由名称,和对应的控制器方法,就可以不用繁琐地写那些路由,和控制器方法了。

为方便展示,我们把数据渲染到视图文件,首先创建 resources/views/events/index.blade.php 视图文件,使用默认的布局文件,填充以下代码:

 @extends('layouts.app')
@section('content')
    <h1>Events</h1>
@endsection  

打开 app/Http/Controllers/EventsController 文件并修改 index 方法:

 public function index()
{
    return view('events.index');
}  

大家看到了,上述方法内是没有数据库数据交互的,我们下面引入模型,并渲染到视图内。在控制器顶部添加如下引用:

 use AppEvent;  

index 方法内填充以下代码:

 $events = Event::all();
return view('events.index')->with('events', $events);  

有了以上的数据,在视图内简单地遍历输出内容,修改视图文件如下:

 <h1>Events</h1>
<ul>
    @forelse ($events as $event)
        <li>{{ $event->name }}</li>
    @empty
        <li>No events found!</li>
    @endforelse
</ul>  

模板文件内 @forelse 方法会判断是否 $events 变量至少有一个元素可供遍历,如果没有就输出 @empty 区块的内容。在浏览器内访问路由地址,输出内容大致如下图。因为使用的 Faker 填充的伪数据,所以看上去是这样的:

3分钟短文:有面子!Laravel教你简单写出专业的API

如果数据量太大,这一页估计要加载很久,列表很长。所以需要分页了。加入分页功能,使用的SQL语句大概是这样的:

 select id, name from events order by id asc limit 10 offset 0;
select id, name from events order by id asc limit 10 offset 10;  

控制器内使用分页功能,简单对模型调用 paginate 方法即可:

 $events = Events::paginate(10);  

每页设置为10条。我们在视图内,要有一个前一页,后一页,以及页码的导航条,也不用我们手动写了。laravel竟然继承到了 paginate 方法所返回的 IlluminatePaginationLengthAwarePaginator 类内,只用在视图内添加这样一行就够了:

 {!! $events->links() !!}  

生成的导航条如下:

3分钟短文:有面子!Laravel教你简单写出专业的API

写在最后

本文介绍了laravel自身继承的资源型url的快捷注册方法和使用方法。通过之前讲过的从路由到控制器,以及视图渲染的方法,引入了分页的概念,以及如何生成人性化的导航条。

Happy coding 🙂

文章来源:智云一二三科技

文章标题:3分钟短文:有面子!Laravel教你简单写出专业的API

文章地址:https://www.zhihuclub.com/79692.shtml

关于作者: 智云科技

热门文章

评论已关闭

27条评论

  1. Diethylstilbestrol and risk of fatal breast cancer in a prospective cohort of US women Chris Riback So describe that focus for me

  2. D NIH 3T3 cells were treated with TGF ОІ for 24 hours or left untreated in the presence of either inactive control compound or NCT 503

  3. At 1600 mg m 2 dose gr 3 hypokalemia with course 2; acute pancreatitis in a patient with non Hodgkin s lymphoma during course 6 22

  4. Representative areas from each tumor were punched and brought into recipient paraffin blocks to construct TMAs consisting of two cores diameter 1 mm of each tumor

  5. The major limitation of conventional nanodrugs is their accumulation in the reticuloendothelial system RES, a group of important immune organs, rather than in the specific tumors they are meant to target

  6. 53, 54 However, the qualities of estrogens are still measured to determine the estrogenicity of compounds Abbreviation CPM, contralateral prophylactic mastectomy

  7. 12 133 and can be summarized as follows A B S T R A C T Most cancer deaths are due to the systemic dissemination of cancer cells and the formation of secondary tumors metastasis in distant organs

  8. LH causes ovulation if you have any eggs left The reaction may be carried out in a suitable organic solvent in the presence of a base

  9. Three alternate sections per animal, spaced 400 Ојm apart were sampled for control analyses Mrs Jill Hervik, a physiotherapist and acupuncturist at the Vestfold Central Hospital Tonsberg, Norway revealed that patients who received traditional Chinese acupuncture had a 50 pct reduction in hot flushes, both during the day and the night, and that this effect continued after the acupuncture ceased

  10. Despite our differing needs, we are lumped in with all breast cancer groups, and worse, we have, in droves, been turned away from early stage groups, pulled aside and whispered to by coordinators, saying you will frighten the early stage women In the stimulated IVF cycle, women were allowed to have a maximum of two embryos replaced into the uterine cavity 2 days after the retrieval and surplus good quality embryos were frozen on the same day

  11. To change this situation and improve the prognosis in TCL, new gene targeted therapies must be developed To be honest I closed my eyes most of the time

  12. Hamdan FH, Johnsen SA Total dose was either 50 Gy in 25 fractions or 48 Gy in 22 fractions

  13. A tracking number is also provided to the customers so they can see the status of their goods

  14. The spin trapping of superoxide with DMPO was conducted using a superoixde generating system consisting of hypoxanthine in the presence of the enzyme xanthine oxidase at pH 7

  15. That is why you re having the problems that you re having with this pandemic in America because it is not being dealt with correctly At that time, there were convincing data from the overview of adjuvant tamoxifen trials showing a clinically worthwhile survival benefit with tamoxifen 2

  16. The B34 trial is designed to provide a definitive answer to this question 9 There are no comparable data for women with metastatic breast cancer

网站地图