New in Twig: Namespaced Classes

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.

Comments

I like that kind of move. Thanks!
What about SwiftMailer? Component also does not have a namespace.
@Michal hi, stay stuned about symfony/mailer 😀
Very nice! Is there a list somewhere so we can do an easy /search/replace/g ?
Cool, with namespaces it looks much better
Rector ready: https://github.com/rectorphp/rector/blob/master/config/level/twig/underscore-to-namespace.yaml
Its breaking major projects globally :-) :-) https://github.com/twigphp/Twig/issues/2886
fixed in 1.38.1 and 2.7.1 (which I've just released).
My 2 cents: https://www.tomasvotruba.cz/blog/2019/04/04/how-to-upgrade-twig-from-underscored-to-namespaces/
Login with SymfonyConnect to post a comment