Routing and Hello world

Posted under » Symfony on 22 Aug 2020

Creating a new page - whether it’s an HTML page or a JSON endpoint - is a two-step process:

Create a route: A route is the URL (e.g. /about) to your page and points to a controller;

Create a controller: A controller is the PHP function you write that builds the page. You take the incoming request information and use it to create a Symfony Response object, which can hold HTML content, a JSON string or even a binary file like an image or PDF.

I think, Symfony is not LAMP friendly. You have to make sure you install the Apache-pack if you want URL-rewrites. (it doesnt use .htacess) If you have Symfony Flex...

composer require apache-pack

There are a few ways to do routing. You can use YAML, XML or PHP Files but it is recommended that you do the annotations way because the routing appears at the controller.

composer require annotations

As your application grows, you’ll eventually have a lot of routes. Symfony includes some commands to help you debug routing issues.

First, the debug:router command lists all your application routes in the same order in which Symfony evaluates them

php bin/console debug:router

----------------  -------  -------  -----  --------------------------------------------
Name              Method   Scheme   Host   Path
----------------  -------  -------  -----  --------------------------------------------
homepage          ANY      ANY      ANY    /
contact           GET      ANY      ANY    /contact
contact_process   POST     ANY      ANY    /contact
blog_show         ANY      ANY      ANY    /blog/{slug}

Route Parameters. The previous examples defined routes where the URL never changes (e.g. /blog). However, it’s common to define routes where some parts are variable. For example, the URL to display some blog post will probably include the title or slug (e.g. /blog/my-first-post or /blog/all-about-symfony).

In Symfony routes, variable parts are wrapped in { ... } and they must have a unique name. For example, the route to display the blog post contents is defined as /blog/{slug}:

<¿php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;  
use Symfony\Component\HttpFoundation\Response;
     
class ArticleController extends AbstractController
{
    /**
     * @Route("/")
     */
    public function homepage()
    {
        return new Response('Hello World!');
    }
    /**
     * @Route("/news/{slug}")
     */
    public function show($slug)
    {
        return new Response(sprintf(
            'Hot topic of the day : "%s"',
            $slug
        ));
    }
}

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data