Symfony News

New in Twig: Namespaced Classes

Fabien Potencier

Contributed by
Fabien Potencier
in #2861, #2862 and #2863.

Twig template engine was originally released in 2008, a year before PHP 5.3 introduced PHP namespaces in June 2009. That's why historically Twig classes never used namespaces:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
namespace App\Twig;

class AppExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return [
            new \Twig_SimpleFilter('...', [this, '...']),
        ];
    }

    // ...
}

In 2017, we added namespaced aliases so you could use namespaces to import Twig classes, but we also maintained the non-namespaced classes, to not break any existing applications. This is how the previous example looks like when using namespaces:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
namespace App\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class AppExtension extends AbstractExtension
{
    public function getFilters()
    {
        return [
            new TwigFilter('...', [this, '...']),
        ];
    }

    // ...
}

Maintaining both ways of working with Twig classes complicates its maintenance unnecessarily, so we've decided that it's time to switch all Twig classes to use PHP namespaces. That's why, starting from the next 2.x version, all non- namespaced classes will be deprecated and they will be removed in Twig 3.x, which is expected to be released during 2019.

This move implies lots of code changes, so please test the development version of Twig 2.x in your real applications and report any issues before we tag its next stable version at the end of next week.


Be trained by Symfony experts - 2019-03-6 Clichy - 2019-03-11 Clichy - 2019-03-11 Clichy


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook