Symfony is a prominent open-source PHP framework renowned for its flexibility, scalability, and a comprehensive suite of reusable components. It empowers developers to construct web applications and APIs with a structured and efficient approach, adhering to the Model-View-Controller (MVC) architectural pattern.
1. **Defining a Route:**
```php use Symfony\Component\Routing\Annotation\Route;
class MyController {
#[Route('/hello/{name}', name: 'hello')] public function hello($name) { return new Response("Hello, $name!"); }} ```
This code defines a route `/hello/{name}` that maps to the `hello` action in the `MyController`.
2. **Rendering a Template:**
```php use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response;
class MyController extends AbstractController {
#[Route('/blog/{slug}', name: 'blog_post')] public function show($slug) { // ... fetch blog post data ...
return $this->render('blog/post.html.twig', [ 'post' => $post, ]); }} ```
This code snippet illustrates how to render a Twig template, `blog/post.html.twig`, passing the `post` data for dynamic content rendering.
3. **Handling a Form Submission:**
```php use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use App\Form\ContactType;
class ContactController extends AbstractController {
#[Route('/contact', name: 'contact')] public function index(Request $request) { $form = $this->createForm(ContactType::class); $form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) { // ... process form data ...
return $this->redirectToRoute('contact_success'); }
return $this->render('contact/index.html.twig', [ 'form' => $form->createView(), ]); }} ```
This code demonstrates the handling of form submissions using Symfony's form component, showcasing how to create, handle requests, and render the form.