Here’s a cheat sheet for Symfony, a PHP web application framework:
Symfony Project Structure
/src
: Contains the source code of your application./config
: Configuration files for the application./var
: Temporary and log files./templates
: Twig templates for rendering views./public
: Web server’s document root.
Routing
Define Route in Controller:
/**
* @Route("/hello/{name}", name="hello")
*/
public function hello($name)
{
// Controller logic
}
Generate URL in Twig:
<a href="{{ path('hello', {'name': 'John'}) }}">Hello John</a>
Controllers
Rendering a View:
return $this->render('template.html.twig', ['variable' => $value]);
Redirecting:
return $this->redirectToRoute('route_name');
Forms
Create a Form Type:
// src/Form/TaskType.php
class TaskType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('task', TextType::class)->add('dueDate', DateType::class);
}
}
Handle Form Submission in Controller:
public function new(Request $request)
{
$task = new Task();
$form = $this->createForm(TaskType::class, $task);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// Process form submission
}
}
Doctrine ORM
Entity Definition:
// src/Entity/Task.php
class Task
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string")
*/
private $task;
// Getters and setters
}
Database Migrations:
php bin/console make:migration
php bin/console doctrine:migrations:migrate
Security
Firewall Configuration:
# config/packages/security.yaml
security:
firewalls:
secured_area:
pattern: ^/admin
http_basic:
realm: "Secured Demo Area"
Roles and Access Control:
# config/packages/security.yaml
security:
access_control:
- { path: ^/admin, roles: ROLE_ADMIN }
Services and Dependency Injection
Define a Service:
# config/services.yaml
services:
app.my_service:
class: App\Service\MyService
Inject Service into Controller:
public function someAction(MyService $myService)
{
// Use the service
}
Commands
Create a Command:
php bin/console make:command
Run Command:
php bin/console my:command
Twig Templating
Render a Variable:
{{ variable }}
Conditionals:
{% if condition %}
{# Do something #}
{% endif %}
Symfony Console
Create a Command:
php bin/console make:command
Run Command:
php bin/console my:command
This Symfony cheat sheet provides a quick overview of some common tasks. Symfony has extensive documentation available, so refer to the Symfony Documentation for more in-depth information.