Symfony学习笔记 - Symfony Documentation - The Basics(1)

1、Doctrine

Symfony中,通过Doctrine完成数据库的相关操作:

  1. 通过环境变量.env,完成数据库的连接设置
  2. 可以通过指令,引导式的完成Entity文件的创建和更改。Entity中,包括字段及ORM属性和getter & setter
    php bin/console make:entity
  3. Migration,完成数据表的创建和更改
    php bin/console doctrine:migrations:migrate
  4. 创建将Entity写入数据库的Controller
    php bin/console make:controller ProductController
  5. Validating Object可以根据创建的table,自动生成验证规则(注意:Validating是单独安装的,不需要Doctrine也可以使用)
  6. 可以通过EntityManager,在Controller中,获取数据(EntityManager是Doctrine一起安装的)
  7. 也可以通过Entity的Repository获取数据(EntityRepository也是跟Doctrine一起按照的)
  8. 可以通过属性的方式,将路由属性中的id直接转换成entity object
    [Route('/product/{id}')] public function showByPk(Product $product): Response { }
  9. 在没有特殊查询的情况下,Doctrine\ORM\EntityRepository可以完成一些基本的操作,比如find()、findBy()、findOneBy()等。如果需要复杂的查询,可以在src/Repository目录下,建一个EntityRepository,比如ProductRepository。
  10. 在Repository中,还可以使用Doctrine的QueryBuilder,通过面向对象的方式写查询:
    class ProductRepository extends ServiceEntityRepository ... $qb = $this->createQueryBuilder('p') ->where('p.price > :price') ->setParameter('price', $price) ->orderBy('p.price', 'ASC'); ...
  11. Doctrine还能管理database relationship

2、Form

Form中的控件,是基于原生的input、select控件创建的,都是SSR渲染创建出来的。如果是要基于Vue、React来创建,那么可以不使用Form Buddle。

  1. 在Controller中,创建Form
    class TaskController extends AbstractController ... $form = $this->createFormBuilder($task) ->add('task', TextType::class) ->add('dueDate', DateType::class) ->add('save', SubmitType::class, ['label' => 'Create Task']) ->getForm(); ...
  2. 显示Form
    return $this->render('task/new.html.twig', [ 'form' => $form, ]);
  3. 处理Form
    推荐使用同一个方法来处理Form的Render和提交。
  4. 验证Form
    可以使用Validator来验证Form