Composer and Twig. The Dynamic Duo for Easy PHP Dev.

Discover the power of Composer and Twig, the dynamic duo that simplifies PHP development.

Understanding PHP, Composer, and Twig is valuable because they play crucial roles in web development. PHP is the backbone of many websites and applications, offering numerous job opportunities. Composer simplifies the management of PHP projects by facilitating the addition of new functionalities and libraries (back-end). Meanwhile, Twig streamlines the process of creating website layouts (front-end). This article aims to educate individuals interested in expanding their knowledge of these essential tools in web development.

Even though Node.js is popular, PHP is still used in many projects, especially in existing websites and applications. Learning PHP, Composer, and Twig can make you a versatile developer and help you understand other programming languages in the future.

It would be nice to know right away which version of Composer is the newest. Then, we can update Composer to that version. This is important because if your composer.json is old, you might have trouble installing new packages like Twig.

By the way, installing Twig with Composer is a smart choice. You probably already have PHP installed on your computer. I have PHP 8.1.27.

php -v

Composer for LAMP development is like NPM for MERN. So, it's important to keep all your packages, their versions, dependencies, and everything else in good working order to avoid future errors and software conflicts.

Run this in your virtual environment on your Linux machine:

composer --version

For example, if the new version is 2.7.2 and you have 1.2.1 installed, you might have trouble installing Twig using composer. So, Composer needs to be updated.

Let's go to the directory where Composer is installed and remove composer config files and the composer cache:

cd /usr/bin
sudo rm -rf composer composer.phar composer-setup.php composer-setup.sig
sudo apt remove composer
rm -rf ~/.composer

After cleaning the system, let's go to the Composer website and follow the command-line installation instructions:

sudo php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
sudo php -r "if (hash_file('sha384', 'composer-setup.php') === 'dac665fdc30fdd8ec78b38b9800061b4150413ff2e3b6f88543c636f7cd84f6db9189d43a81e5503cda447da73c7e5b6') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
sudo php composer-setup.php
sudo php -r "unlink('composer-setup.php');"

Now we have composer.phar in your bin directory and we can run:

composer.phar --version

Or we can remove .phar and make the composer file executable:

sudo mv composer.phar composer
sudo chmod +x composer

Let's add the directory to the shell's configuration:

nano ~/.bashrc

Add this to the end of the file:

export PATH=$PATH:/usr/bin

And then in the terminal:

source ~/.bashrc

Now you can use the updated Composer to initialize and install Twig. Go to your project directory, let's say:

cd /home/twig
composer init

You'll find composer.json config file and /vendor directory, which is similar to /node_modules. Now let's add Twig to the project:

composer require "twig/twig:^3.0"

Twig is a part of Symfony and a very convenient templating engine, which I really like using in my PHP projects.

After installing Twig, let's create /public directory and go into it.

cd /public
touch index.php

Assuming you already pointed your web server to /home/twig/public, you can see the result after updating the following index.php file:

    require_once '../vendor/autoload.php';

    $loader = new \Twig\Loader\FilesystemLoader("templates");
    $twig = new \Twig\Environment($loader);

    echo $twig->render(
        "index.twig", [
            "greeting" => "What's up, world?"
        ]
    );

and after creating our first .twig template (see above how the loader points to the templates directory):

mkdir templates
cd templates
touch index.twig

Update the index.twig template file:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>{{ greeting }}</title>
    </head>
    <body>
        <p>{{ greeting | raw }}</p>
    </body>
    </html>

Also, don't forget to add support for Twig in Visual Studio Code and have it recognized as HTML. Go to extensions, search and install "Twig Language 2". After that, you should see syntax highlighting for Twig files (.twig) in Visual Studio Code, and it should be recognized as HTML.

Now, why do I like using Twig?

First of all, I like its extensibility. I can use filters and functions. For example, I frequently use "raw" to allow HTML tags or "truncate" to limit the number of characters, or "slice", "date", "capitalize". And functions like "include", "asset", "range", "cycle" and "attribute".

Second, Twig automatically escapes output by default, helping to prevent XSS (cross-site scripting) attacks. This means you don't have to manually escape variables with htmlspecialchars() function. This makes your templates more secure.

Third, Twig supports template inheritance, allowing you to define a base template with common elements and extend it in child templates.

In general, I like how Twig can send data to the template and its built-in features that simplify the development and creation of reusable components and how it can contribute to the creation of entire themes for the website.

Good luck!
May all your endeavors be successful, and may your code always run smoothly.
Best Regards,
Artem

473