基于symfony搭建REST API(一)

  1. 安装两个recipes
composer req symfony/serializer
compser req friendsofsymfony/rest-bundle
  1. 创建一个实体,这里以User代替,并添加相应的字段
~ cd 你的工作目录/
~ bin/console  make:entity
 Class name of the entity to create or update (e.g. OrangeJellybean):
 > User
Add another property? Enter the property name (or press <return> to stop adding fields):
 > name 

 Field type (enter ? to see all types) [string]:
 > 

 Field length [255]:
 > 

 Can this field be null in the database (nullable) (yes/no) [no]:
 > no

 updated: src/Entity/User.php

 Add another property? Enter the property name (or press <return> to stop adding fields):
 > pass
  1. User实例生成后,再根据类生成相应的user表
~ bin/console make:migration  
#成功后再执行下面的命令
~ bin/console doctrine:migrations:migrate
#输入y,user表就生成了
  1. 目录结构
  • 修改restbundle配置文件
#config/packages/fost_rest.yaml
fos_rest:
    view:
        view_response_listener:  true
    format_listener:
        rules:
            - { path: ^/api, prefer_extension: true, fallback_format: json, priorities: [ json] }
            - { path: ^/, fallback_format: html }
  • 修改annotations配置,使web路径和api路径区分开
#config/routes/annotations.yaml
#名字不重要,可以随便命名
web_controller:
    resource: ../../src/Controller/Web/
    type: annotation
rest_controller:
    resource: ../../src/Controller/Rest/
    type: annotation
    prefix: /api
  • Controller目录结构


    WechatIMG4.jpeg

    在Rest下创建了v1这个目录,用于区分不同版本的api

到这里,准备工作已完成。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,212评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,178评论 6 342
  • 初次相遇 考入初中后,我终于离开我们那个小村庄,可以到外面的世界看看了,内心无比的兴奋和激动。我的...
    早起写作阅读 2,790评论 0 0
  • 比照着一个好看的街拍图,用红色中性笔画了上面那幅画。然后,人脸画残了,人家潇洒的气质也没画出来…… 但是每一次拾起...
    王小常阅读 5,060评论 4 7
  • 因为在公司要负责修改很多一言难尽的ppt,很多小伙伴问我如何做好ppt,但我想他们的实际需求可能是如何快速套模板做...
    胖子向阅读 5,932评论 6 25

友情链接更多精彩内容