If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.
With a Subscription, click any sentence in the script to jump to that part of the video!
Login SubscribeOur code, specifically the code in these two classes, does not follow the dependency inversion principle. Why not? Let's go through the two parts of the definition, one by one.
The first part is:
High level modules should not depend on low level modules. Both should depend on abstractions, for example, interfaces.
This is a fancy way of saying that classes should depend on interfaces instead of concrete classes. Yep! This part of the rule is that simple. It says that instead of type-hinting - so "depending on" - the concrete RegexSpamWordHelper
, we should type-hint an interface.
Okay! So we just need to create a new interface, make RegexSpamWordHelper
implement the interface, then change the type-hint to use that interface, right? Yes, exactly!
But... the second part of DIP tells us something about how we should create and design that interface. That part says:
Abstractions should not depend on details. Details - which are concrete implementations - should depend on abstractions.
We simplified this to:
An interface should be designed by the class that will use it, not by the class that will implement it.
Let me explain. The most natural way to create the new interface would be to look at the class that will implement it - so RegexSpamWordHelper
- and create an interface that matches it! So a RegexSpamWordHelperInterface
with a getMatchedSpamWords()
method. Done!
But by doing this, we are allowing the interface to, sort of, be "owned" by the lower level class, sometimes known as the "details" class. In other words, the way the interface looks is being "controlled" by the lower-level RegexSpamWordHelper
class.
But DIP says that the higher level class - CommentSpamManager
- should be in charge of creating the interface, allowing it to design its dependency in just the way that it wants.
Let's put this into practice. If you look at CommentSpamManager
, all it really needs is to be able to call a method that will return the number of spammy words... because that count is ultimately all we use: we don't really need the matched words themselves.
So in the Comment/
directory, which I'm using to highlight that this interface is owned by CommentSpamManager
, create a new interface: select PHP class, change to interface and call it, how about, CommentSpamCounterInterface
.
Inside, add one method: public function countSpamWords()
, which will accept the string $content
and return an int
.
... lines 1 - 4 | |
interface CommentSpamCounterInterface | |
{ | |
public function countSpamWords(string $content): int; | |
} |
Beautiful! Notice that just by inverting, who we think should be in charge of creating the interface - or who should "own" it - we ended up with a very different result. Instead of forcing the interface to look like the low level RegexSpamWordHelper
class, that class is now going to be forced to change itself to implement the interface.
Add implements CommentSpamCounterInterface
, then I'll go to Code -> Generate - or Command + N on a Mac - and select "Implement Methods" to generate countSpamWords()
. Inside, return the count()
of $this->getMatchedSpamWords($content)
.
... lines 1 - 6 | |
class RegexSpamWordHelper implements CommentSpamCounterInterface | |
{ | |
public function countSpamWords(string $content): int | |
{ | |
return count($this->getMatchedSpamWords($content)); | |
} | |
... lines 13 - 34 | |
} |
Back in CommentSpamManager
, let's follow the first part of DIP and change this to depend on the new interface. Change the type-hint to CommentSpamCounterInterface
... change the type on the property... and let's also rename the property itself to be more clear: call it $spamWordCounter
. Rename the argument too.
... lines 1 - 6 | |
class CommentSpamManager | |
{ | |
private CommentSpamCounterInterface $spamWordCounter; | |
public function __construct(CommentSpamCounterInterface $spamWordCounter) | |
{ | |
$this->spamWordCounter = $spamWordCounter; | |
} | |
... lines 15 - 24 | |
} |
Down in validate()
, change $badWordsOnComment
to $badWordsCount
. Then, instead of calling getMatchedSpamWords()
, call the new countSpamWords()
. Below, we don't need the count()
anymore: just check if $badWordsCount
is greater than or equal to 2.
... lines 1 - 15 | |
public function validate(Comment $comment): void | |
{ | |
... line 18 | |
$badWordsCount = $this->spamWordCounter->countSpamWords($content); | |
... line 20 | |
if ($badWordsCount >= 2) { | |
... line 22 | |
} | |
} | |
... lines 25 - 26 |
Congratulations! Our code now follows the two parts of the dependency inversion principle! One, our high level class - CommentSpamManager
- depends on an interface. And two, that interface was designed for - and is controlled by - the high-level class, instead of being designed and controlled by the low level, or "details" class: RegexSpamWordHelper
.
Before we talk about the takeaways from the dependency inversion principle, I want to mention two things.
First, over in RegexSpamWordHelper
, you are allowed to have this public function getMatchedSpamWords()
method if you're using it somewhere else in your code. Since we're not, I'm going to clean things up and make it private
.
... lines 1 - 6 | |
class RegexSpamWordHelper implements CommentSpamCounterInterface | |
{ | |
... lines 9 - 13 | |
private function getMatchedSpamWords(string $content): array | |
{ | |
... lines 16 - 22 | |
} | |
... lines 24 - 34 | |
} |
Second... well... this is more of a question: will Symfony know which service to autowire when it sees the CommentSpamCounterInterface
type-hint? Will it know that it should actually pass us the RegexSpamWordHelper
service?
Actually... it will! Find your terminal and run:
php bin/console debug:autowiring Comment --all
I'm passing --all
just so we can see all the results. And... this proves it! As this shows, when Symfony sees a CommentSpamCounterInterface
type-hint, it will autowire the RegexSpamWordHelper
service.
This works thanks to a nice feature inside Symfony's container. If Symfony sees an interface in our code - like CommentSpamCounterInterface
- and only one of our classes implements it, then it automatically assumes that this class should be autowired for that interface. If you ever created a second class that implemented the interface, Symfony would throw a clear exception telling us that we need to choose which one to autowire.
Next: let's talk about the takeaways of the dependency inversion principle, and also... what that word "inversion" means and doesn't mean.
Hey @EricPoe
In this code block, you can see the full code of CommentSpamManager
https://symfonycasts.com/screencast/solid/dip-refactoring#codeblock-3c54572a60
The name of the private property is still $spamWordCounter
but it's type-hinted with CommentSpamCounterInterface
- Unless I'm missing something the code won't break with this refactoring
Cheers!
// composer.json
{
"require": {
"php": ">=8.1",
"ext-ctype": "*",
"ext-iconv": "*",
"composer/package-versions-deprecated": "^1.11", // 1.11.99.1
"doctrine/annotations": "^1.0", // 1.12.1
"doctrine/doctrine-bundle": "^2", // 2.3.1
"doctrine/doctrine-migrations-bundle": "^3", // 3.1.1
"doctrine/orm": "^2", // 2.8.4
"knplabs/knp-time-bundle": "^1.15", // v1.16.0
"phpdocumentor/reflection-docblock": "^5.2", // 5.2.2
"sensio/framework-extra-bundle": "^6.0", // v6.1.2
"symfony/console": "5.2.*", // v5.2.6
"symfony/dotenv": "5.2.*", // v5.2.4
"symfony/flex": "^1.9", // v1.18.7
"symfony/form": "5.2.*", // v5.2.6
"symfony/framework-bundle": "5.2.*", // v5.2.6
"symfony/http-client": "5.2.*", // v5.2.6
"symfony/mailer": "5.2.*", // v5.2.6
"symfony/property-access": "5.2.*", // v5.2.4
"symfony/property-info": "5.2.*", // v5.2.4
"symfony/security-bundle": "5.2.*", // v5.2.6
"symfony/serializer": "5.2.*", // v5.2.4
"symfony/twig-bundle": "5.2.*", // v5.2.4
"symfony/validator": "5.2.*", // v5.2.6
"symfony/webpack-encore-bundle": "^1.6", // v1.11.1
"symfony/yaml": "5.2.*", // v5.2.5
"twig/cssinliner-extra": "^3.3", // v3.3.0
"twig/extra-bundle": "^2.12|^3.0", // v3.3.0
"twig/twig": "^2.12|^3.0" // v3.3.0
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.2", // 3.4.0
"fakerphp/faker": "^1.13", // v1.14.1
"symfony/debug-bundle": "^5.2", // v5.2.4
"symfony/maker-bundle": "^1.13", // v1.30.2
"symfony/monolog-bundle": "^3.0", // v3.7.0
"symfony/stopwatch": "^5.2", // v5.2.4
"symfony/var-dumper": "^5.2", // v5.2.6
"symfony/web-profiler-bundle": "^5.2" // v5.2.6
}
}
I think that
CommentSpamManager
should keep its private property calledspamWordCounter
(private CommentSpamManager::spamWordCounter
) instead ofCommentSpamInterface
(private CommandSpamManager::CommentSpamInterface
). As written, the code will break because there is no property calledCommentSpamManager::spamWordCounter
.