Skip to content

Instantly share code, notes, and snippets.

@BillClinton
Last active March 30, 2020 16:50
Show Gist options
  • Save BillClinton/df10f6ba48f9a5b7fbe6158ab3e85135 to your computer and use it in GitHub Desktop.
Save BillClinton/df10f6ba48f9a5b7fbe6158ab3e85135 to your computer and use it in GitHub Desktop.
symfony commands

Development

Require server

composer require server --dev

Start local server

symfony server:start

Show Routes

bin/console debug:router

Project Creation

Create Project w/ version

composer create-project symfony/website-skeleton:^4.4 rest_api_project

Install MakerBundle (to use make command)

composer require symfony/maker-bundle --dev

Create Schema:

bin/console doctrine:schema:create

Create controller:

bin/console make:controller

Create or update Entity:

bin/console make:entity

Forms

Enable forms

composer require symfony/form

Create form:

bin/console make:form

API Platform setup:

composer require api

REST API setup (old):

Create project

composer create-project symfony/skeleton:^4.4 my_rest_api

Install required bundles

move into project directory and execute the following:

composer require jms/serializer-bundle
composer require friendsofsymfony/rest-bundle
composer require sensio/framework-extra-bundle
composer require symfony/validator
composer require symfony/form
composer require symfony/orm-pack

Configure database access

In the .env file:

DATABASE_URL=mysql://db_user:[email protected]:3306/db_name?serverVersion=5.7

Create an entity and generate table:

bin/console make:entity
bin/console doctrine:schema:create

Create form

bin/console make:form

Configure FOS_Rest

Add the following to config/packages/fos_rest.yaml:

# Read the documentation: https://symfony.com/doc/master/bundles/FOSRestBundle/index.html
fos_rest:
    routing_loader:
        default_format: json
        include_format: false
    body_listener: true
    format_listener:
          rules:
              - { path: '^/', priorities: ['json'], fallback_format: json, prefer_extension: false }
    param_fetcher_listener: true
    access_denied_listener:
        json: true
    view:
        view_response_listener: 'force'
        formats:
            json: true

Add the following to the end of config/services.yaml:

sensio_framework_extra.view.listener:
    alias: Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener

to address FOS/Sensio incompatibility: FriendsOfSymfony/FOSRestBundle#1768

Create controller

eg: src/Controller/BookController.php

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations as Rest;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use App\Entity\Book;
use App\Form\BookType;

/**
 * Book controller.
 * @Route("/api", name="api_")
 */
class BookController extends FOSRestController
{
  /**
   * Lists all Books.
   * @Rest\Get("/books")
   *
   * @return Response
   */
  public function getBookAction()
  {
    $repository = $this->getDoctrine()->getRepository(Book::class);
    $books = $repository->findall();
    return $this->handleView($this->view($books));
  }
  /**
   * Create Book.
   * @Rest\Post("/book")
   *
   * @return Response
   */
  public function postBookAction(Request $request)
  {
    $book = new Book();
    $form = $this->createForm(BookType::class, $book);
    $data = json_decode($request->getContent(), true);
    $form->submit($data);
    if ($form->isSubmitted() && $form->isValid()) {
      $em = $this->getDoctrine()->getManager();
      $em->persist($book);
      $em->flush();
      return $this->handleView($this->view(['status' => 'ok'], Response::HTTP_CREATED));
    }
    return $this->handleView($this->view($form->getErrors()));
  }
}

Set up OAuth2 authorization

Misc:

composer require friendsofsymfony/rest-bundle

bin/console server:stop

bin/console make:controller
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment