If we are developing a library that is used by multiple applications, then we have to be very careful when renaming class methods, removing unnecessary code or doing other breaking changes. Otherwise, we might break client's application.
This tutorial shows how to deprecate code in Symfony 7 application.
Make sure you have installed the PHPUnit Bridge for testing purpose:
composer require --dev symfony/phpunit-bridge
Let's say we have an integration test for checking code deprecations:
<?php
namespace App\Tests\Service;
use App\Service\NewsletterManager;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
class NewsletterManagerTest extends KernelTestCase
{
public function testSend(): void
{
$manager = self::getContainer()->get(NewsletterManager::class);
self::assertTrue($manager->send());
}
}
We can run tests as follows:
./vendor/bin/phpunit
Deprecating a method
If you want to deprecate the class method, you can use trigger_deprecation
function. It will trigger a deprecation notice. This function accepts package name, package version, and message of the deprecation.
<?php
namespace App\Service;
class NewsletterManager
{
public function send(): bool
{
trigger_deprecation(
'my-vendor/my-package',
'1.1',
'NewsletterManager::send method is deprecated, use XXX instead.'
);
// Method implementation ...
return true;
}
}
Run tests to see deprecation notice. Output:
OK (1 test, 1 assertion)
Remaining self deprecation notices (1)
1x: Since my-vendor/my-package 1.1: NewsletterManager::send method is deprecated, use XXX instead.
1x in NewsletterManagerTest::testSend from App\Tests\Service
Deprecating a class
If you want to deprecate a whole class, the trigger_deprecation
function should be placed after the use
declarations.
<?php
namespace App\Service;
// use Symfony\Component\...;
trigger_deprecation(
'my-vendor/my-package',
'1.1',
'NewsletterManager class is deprecated, use XXX instead.'
);
class NewsletterManager
{
public function send(): bool
{
// Method implementation ...
return true;
}
}
Deprecating a template
The Twig template can be deprecated by using deprecated
tag. It accepts the message of the deprecation.
{% deprecated 'The email.html.twig template is deprecated, use XXX instead.' %}
<?php
namespace App\Service;
use Twig\Environment;
class NewsletterManager
{
public function __construct(private Environment $environment)
{
}
public function send(): bool
{
$content = $this->environment->render('email.html.twig');
// Method implementation ...
return true;
}
}
Leave a Comment
Cancel reply