Community for developers to learn, share their programming knowledge. Register!
Create First Symfony Project

Creating a Simple Calculator using Symfony


In this article, you can get training on creating a simple calculator application using Symfony, one of the most popular PHP frameworks. Symfony provides a robust structure and a set of reusable components that can help developers build applications efficiently. By the end of this tutorial, you will have a functional calculator that performs basic arithmetic operations, which serves as a solid introduction to Symfony's capabilities.

Setting Up Your Development Environment

Before diving into the code, it’s crucial to set up your development environment. Ensure you have the following prerequisites:

PHP: Symfony requires PHP 7.2.5 or higher. You can check your PHP version with:

php -v

Composer: Symfony uses Composer for dependency management. Install Composer if you haven’t already. Follow the instructions on the Composer website.

Symfony CLI: Installing the Symfony CLI tool simplifies project creation and management. You can install it by following the Symfony CLI installation guide.

Creating a New Symfony Project

Once your environment is ready, you can create a new Symfony project. Open your terminal and run:

symfony new calculator --full

This command creates a new Symfony project named "calculator" with all the necessary dependencies and configurations. Navigate into the project directory:

cd calculator

Now, you can start your local server using:

symfony server:start

Your application should now be accessible at http://localhost:8000.

Understanding Symfony Directory Structure

Familiarizing yourself with the Symfony directory structure is essential for effective development. Here’s a brief overview:

  • config/: Contains configuration files for services, routing, and environment variables.
  • src/: Where your PHP code resides, including controllers, entities, and services.
  • templates/: This directory holds your Twig templates for rendering HTML.
  • public/: The web server’s document root, containing the index.php file and assets like images, CSS, and JavaScript.
  • var/: Used for cache and logs, generated automatically during the application lifecycle.

Understanding this structure will help you navigate your project efficiently.

Creating the Calculator Controller

Next, let's create a controller that will handle the calculator logic. In Symfony, controllers are responsible for processing requests and returning responses. Create a new file named CalculatorController.php in the src/Controller/ directory:

// src/Controller/CalculatorController.php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class CalculatorController extends AbstractController
{
    /**
     * @Route("/calculator", name="calculator")
     */
    public function index(Request $request): Response
    {
        return $this->render('calculator/index.html.twig');
    }
}

In this code, we define a route /calculator that maps to the index method, which renders the calculator template.

Building the Calculator Form

To handle user input, we need to create a form. Symfony forms are powerful and make form validation easy. First, create a form class in src/Form/CalculatorType.php:

// src/Form/CalculatorType.php

namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;

class CalculatorType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('number1', NumberType::class, ['label' => 'First Number'])
            ->add('number2', NumberType::class, ['label' => 'Second Number'])
            ->add('calculate', SubmitType::class, ['label' => 'Calculate']);
    }
}

This form consists of two number inputs and a submit button. Next, we need to update our controller to handle this form.

Implementing Calculation Logic

Now that we have the form set up, let’s modify the CalculatorController to process the form input and perform calculations. Update the index method:

// src/Controller/CalculatorController.php

use App\Form\CalculatorType;

public function index(Request $request): Response
{
    $form = $this->createForm(CalculatorType::class);
    $form->handleRequest($request);

    $result = null;

    if ($form->isSubmitted() && $form->isValid()) {
        $data = $form->getData();
        $result = $data['number1'] + $data['number2']; // Perform addition
    }

    return $this->render('calculator/index.html.twig', [
        'form' => $form->createView(),
        'result' => $result,
    ]);
}

In this implementation, we check if the form is submitted and valid. If it is, we retrieve the values, perform the addition, and pass the result to the template.

Creating the Calculator Templates

Next, create the template to render the calculator form and show the results. Create a new file at templates/calculator/index.html.twig:

{# templates/calculator/index.html.twig #}

<h1>Simple Calculator</h1>
{{ form_start(form) }}
    {{ form_widget(form) }}
    <button type="submit">Calculate</button>
{{ form_end(form) }}

{% if result is not null %}
    <h2>Result: {{ result }}</h2>
{% endif %}

This template displays the form and, if present, the result after performing the calculation.

Styling the Calculator Application

To enhance the user experience, you might want to add some styling. Create a styles.css file in the public/css/ directory and link it in your template:

<link rel="stylesheet" href="{{ asset('css/styles.css') }}">

In your styles.css file, you can add basic styles:

body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 20px;
}

h1 {
    color: #333;
}

form {
    background: #fff;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

Testing the Calculator Functionality

After implementing the calculator, it’s important to test its functionality. Open your web browser and navigate to http://localhost:8000/calculator. Enter two numbers and click "Calculate." The result should display below the form. Ensure that your application handles various inputs correctly, including edge cases like invalid numbers.

Deploying the Calculator Application

Once you’re satisfied with the functionality, you can deploy your application. Here are the general steps for deploying a Symfony application:

  • Choose a Hosting Provider: Select a provider that supports PHP and Symfony, such as DigitalOcean, Heroku, or AWS.
  • Set Up the Server: Configure your server environment with the necessary PHP version and extensions.
  • Deploy Your Code: You can use Git for version control and deploy your code to the server. Make sure to run composer install on the server to install dependencies.
  • Configure Environment Variables: Set up your environment variables in the .env file or directly in your server configuration.
  • Set Up a Database: If your application requires a database, configure it accordingly.
  • Launch Your Application: Once everything is set, point your domain to your server and visit your application.

Summary

In this article, we explored how to create a simple calculator application using Symfony. We covered setting up the development environment, creating a new Symfony project, building a calculator form, implementing calculation logic, and deploying the application. This project serves as a practical introduction to Symfony's powerful features and can serve as a foundation for more complex applications. With this knowledge, you can confidently embark on building your first Symfony project! For further reading and resources, refer to the Symfony documentation to deepen your understanding of the framework.

Last Update: 29 Dec, 2024

Topics:
Symfony