基于symfony搭建REST API

基于symfony搭建REST API(一)

2018-11-26  本文已影响156人  又起风了_
  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. 目录结构
#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 }
#config/routes/annotations.yaml
#名字不重要,可以随便命名
web_controller:
    resource: ../../src/Controller/Web/
    type: annotation
rest_controller:
    resource: ../../src/Controller/Rest/
    type: annotation
    prefix: /api

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

上一篇 下一篇

猜你喜欢

热点阅读