Skip to content

Instantly share code, notes, and snippets.

@ianlintner-wf
Last active August 29, 2015 14:02
Show Gist options
  • Select an option

  • Save ianlintner-wf/a4445772dde8a694bf97 to your computer and use it in GitHub Desktop.

Select an option

Save ianlintner-wf/a4445772dde8a694bf97 to your computer and use it in GitHub Desktop.

Symfony Training Cheat Sheet

This sheet is a quick overview on generate a basic application and then adding scaffolding.

##TOC

Create Bundle

  • Create Folder
    • e.g. src/DrupalCon/FirstBundle
  • Add Bundle to kernel
    • e.g. app/Resources/AppKernel.php
    • append to bundles array
      $bundles = array(
      ...
      new DrupalCon\FirstBundle\FirstBundle(),
      );
  • Create Routing File
    • e.g. src/DrupalCon/FirstBundle/resources/config/routing.yml

      _first_hello:
        resource: "@FirstBundle/Resources/config/routing.yml"
        prefix:   /
  • Create Controller
    • e.g. src/DrupalCon/FirstBundle/controller/HelloController.php
      <?php
      // src/DrupalCon/FirstBundle/Controller/HelloController.php
      namespace DrupalCon\FirstBundle\Controller;
      
      use Symfony\Component\HttpFoundation\Response;
      
      use Symfony\Bundle\FrameworkBundle\Controller\Controller;
      
      
      class HelloController extends Controller
      {
        public function indexAction($name)
        {
          return $this->render(
            'FirstBundle:Hello:index.html.twig',
            array('name' => $name)
          );
      
          //return new Response('<html><body>Hello '.$name.'!</body></html>');
      
      
          // render a PHP template instead
          // return $this->render(
          //     'AcmeHelloBundle:Hello:index.html.php',
          //     array('name' => $name)
          // );
        }
      }
  • Create View (TWIG)
    • e.g. src/DrupalCon/FirstBundle/resources/views/Hello/index.html.twig
     {# src/DrupalCon/FirstBundle/Resources/views/Hello/index.html.twig #}
     {% extends '::base.html.twig' %}
    
     {% block body %}
         <h1>Hello {{ name }}!</h1>
     {% endblock %}
  • Add Route information to router
    • e.g. app/config/routing_dev.yml
      # src/DrupalCon/FirstBundle/Resources/config/routing.yml
      hello:
          path:     /hello/{name}
          defaults: { _controller: FirstBundle:Hello:index }

Create Scaffolding

  • Create Crud
    • e.g. php app/console generate:doctrine:crud
    • FirstBundle:Product
    • Controller is generated using the annotation for routing in controller
       /**
       * Lists all Product entities.
       *
       * @Route("/", name="product")
       * @Method("GET")
       * @Template()
       */
      public function indexAction()
      {
         ...
      }
  • Create Entity
    • e.g. php app/console generate:doctrine:entity
    • FirstBundle:Product
    • name
    • string
    • 255
    • price
    • float
  • Add route to
    • e.g. app/config/routing_dev.yml
    • code:
      firstbundle_product:
        resource: "@FirstBundle/Controller"
        type: annotation 
  • Verify DB Connection works
    • app/config/parameters.yml
      parameters:
        database_driver: pdo_mysql
        database_host: 127.0.0.1
        database_port: null
        database_name: symfony
        database_user: your_db_user
        database_password: ********
  • Generate Schema (Creates DB)
    • php app/console doctrine:schema:create
  • Test to see if it works
    • route: /products

JSON

  • Example

  • Add use to ProductController.php

    use Symfony\Component\HttpFoundation\Response;
  • Add json function to ProductController.php

    /**
       * Finds and displays a Product entity.
       *
       * @Route("/{id}.json", name="product_show_json")
       * @Method("GET")
       */
      public function showJsonAction($id)
      {
          $em = $this->getDoctrine()->getManager();
    
          /** @var Product $product */
          $product = $em->getRepository('FirstBundle:Product')->find($id);
    
          if (!$product) {
              throw $this->createNotFoundException('Unable to find Product entity.');
          }
    
          $data = array(
              'id' => $product->getId(),
              'name' => $product->getName(),
              'price' => $product->getPrice(),
          );
          $json = json_encode($data);
    
          return new Response($json);
      }

Create Service

  • Create ProductSerializer.php class and take method to transform object JSON route above into function body.

    <?php
    
    namespace DrupalCon\FirstBundle\Business;
    
    class ProductSerializer {
      public function serialize($product) {
        $data = array(
          'id' => $product->getId(),
          'name' => $product->getName(),
          'price' => $product->getPrice(),
        );
        $json = json_encode($data);
        return $json;
      }
    
    } 
  • Add use to ProductController.php

    use DrupalCon\FirstBundle\Business\ProductSerializer;
  • Update ProductController.php with new serializer class

        /**
       * Finds and displays a Product entity.
       *
       * @Route("/{id}.json", name="product_show_json")
       * @Method("GET")
       */
      public function showJsonAction($id)
      {
        $em = $this->getDoctrine()->getManager();
    
        /** @var Product $product */
        $product = $em->getRepository('FirstBundle:Product')->find($id);
    
        if (!$product) {
          throw $this->createNotFoundException('Unable to find Product entity.');
        }
    
        $productSerializer = new ProductSerializer();
        return new Response($productSerializer->serialize($product));
      }
  • Move ProductSerializer.php to src/[BundleRoot]/Service/ProductSerializer.php

  • Remove use in ProductController

    use DrupalCon\FirstBundle\Business\ProductSerializer;
  • Append product serializer class as service in app/config/config.yml

 services:
  my.product_serializer:
    class: DrupalCon\FirstBundle\Service\ProductSerializer
    arguments: []
  • Convert ProductController.php class new Object into service container call.

    //$productSerializer = new ProductSerializer();
    $productSerializer = $this->container->get('my.product_serializer');

##Dependency Injection

  • Create a constructor for ProductSerializer that takes object e.g. Router Service

    class ProductSerializer {
      private $router;
      public function __construct($router) {
        $this->router = $router;
      }
      
      //...
  • Update ProductSerializer.php class to use the service.

    //...
    
    public function serialize($product) {
      $url = $this->router->generate(
        'product_show',
        array('id' => $product->getId())
      );
      $data = array(
        'id' => $product->getId(),
        'name' => $product->getName(),
        'price' => $product->getPrice(),
        'url' => $url,
      );
      $json = json_encode($data);
      return $json;
    }
    
    //...
  • Update Service definition in /App/Config/config.yml to accept router as an argument for constructor

    #...
    
    services:
    my.product_serializer:
      class: DrupalCon\FirstBundle\Service\ProductSerializer
      arguments: [@router]

##Debugs

  • php app/console route:debug
  • php app/console container:debug
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment