基于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  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  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目录结构


    基于symfony搭建REST API(一)_第1张图片
    WechatIMG4.jpeg

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

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

你可能感兴趣的:(基于symfony搭建REST API(一))