How to create a new controller in Symfony?

by elise_daugherty , in category: PHP Frameworks , a year ago

How to create a new controller in Symfony?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , a year ago

@elise_daugherty 

To create a new controller in Symfony, you can follow these steps:

  1. Create a new PHP class in the src/Controller directory of your Symfony project. For example, you can create a file called MyController.php.
  2. In this new file, define a new class that extends Symfony's AbstractController class. For example:
1
2
3
4
5
6
use SymfonyBundleFrameworkBundleControllerAbstractController;

class MyController extends AbstractController
{
    // ...
}


  1. Inside the MyController class, you can define methods that will be used to handle requests. For example, you can create a method called index():
1
2
3
4
5
6
public function index()
{
    return $this->render('my/index.html.twig', [
        'controller_name' => 'MyController',
    ]);
}


  1. In this example, the index() method is using the $this->render() method to render a Twig template called index.html.twig. You can create this template in the templates/my directory of your project.
  2. Finally, you can add a route to your new controller by editing the config/routes.yaml file in your project. For example, you can add the following route:
1
2
3
my_route:
    path: /my-route
    controller: AppControllerMyController::index


This route will map the /my-route URL to the index() method of your MyController class. You can now access your new controller by visiting http://localhost/my-route in your browser.