PHP

  minte9
REMEMBERS




Last update:   18-05-2022

Project

Create a skeleton project named routes.
 
# Routes project

composer create-project symfony/skeleton routes

cd routes/public/
php -S localhost:8000

http://localhost:8000
    # Welcome to Symfony

Routes

Add entries in config/routes.yaml
 
controllers:
    resource: ../src/Controller/
    type: annotation

kernel:
    resource: ../src/Kernel.php
    type: annotation

index:
    path: /
    controller: 'App\Controller\DefaultController::index'

hello:
    path: /hello/{name}
    controller: 'App\Controller\DefaultController::hello'
    defaults:
        name: 'World'

page:
    path: /page/{id}
    controller: 'App\Controller\DefaultController::page'
    requirements: 
        id: \d+

page_slug:
    path: /{catg}/{slug}-{id}
    controller: 'App\Controller\DefaultController::page_slug'
    requirements:
        catg: '[a-z0-9-]+'
        slug: '[a-z0-9-]+'
        id: \d+

url:
    path: /url
    controller: 'App\Controller\DefaultController::url'

Controller

Add default controller in src/Controller/
 
/**
 * Default Controller:
 * 
 * src/Controller/DefaultController.php
 * 
 * http://localhost:8000/                           # Index page
 * http://localhost:8000/hello                      # Hello World
 * http://localhost:8000/page                       # Page 1
 * http://localhost:8000/page/2                     # Page 2
 * http://localhost:8000/php/symfony-6              # php, symfony, 6
 * http://localhost:8000/url                        # /java/threads-1001
 */

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class DefaultController extends AbstractController
{
    public function index()
    {
        return new Response("Index page");
    }

    public function hello($name)
    {
        return new Response("Hello $name");
    }

    public function page($id)
    {
        return new Response("Page $id");
    }

    public function page_slug($catg, $slug, $id)
    {
        return new Response("$catg, $slug, $id");
    }

    public function url() {

        $link = $this->generateUrl('page_slug', [
            'catg' => 'java',
            'slug' => 'threads',
            'id' => 1001,
        ]);

        return new Response($link);
    }
}

Questions     github Symfony
Annotations
        A B C D E F
🔔
1/2