Use PHP constructor property promotion

This commit is contained in:
Peter Kokot
2023-05-24 08:19:33 +02:00
parent 6513260001
commit 003bb06c7e
3 changed files with 6 additions and 12 deletions

View File

@@ -29,6 +29,7 @@ class MysqlAdapter {}
{% endhighlight %} {% endhighlight %}
This code can be refactored to use Dependency Injection and therefore loosen the dependency. This code can be refactored to use Dependency Injection and therefore loosen the dependency.
Here, we inject the dependency in a constructor and use the [constructor property promotion][php-constructor-promotion] so it is available as a property across the class:
{% highlight php %} {% highlight php %}
<?php <?php
@@ -36,11 +37,8 @@ namespace Database;
class Database class Database
{ {
protected $adapter; public function __construct(protected MySqlAdapter $adapter)
public function __construct(MySqlAdapter $adapter)
{ {
$this->adapter = $adapter;
} }
} }
@@ -50,3 +48,5 @@ class MysqlAdapter {}
Now we are giving the `Database` class its dependency rather than creating it itself. We could even create a method Now we are giving the `Database` class its dependency rather than creating it itself. We could even create a method
that would accept an argument of the dependency and set it that way, or if the `$adapter` property was `public` we that would accept an argument of the dependency and set it that way, or if the `$adapter` property was `public` we
could set it directly. could set it directly.
[php-constructor-promotion]: https://www.php.net/manual/en/language.oop5.decon.php#language.oop5.decon.constructor.promotion

View File

@@ -82,11 +82,8 @@ namespace Database;
class Database class Database
{ {
protected $adapter; public function __construct(protected AdapterInterface $adapter)
public function __construct(AdapterInterface $adapter)
{ {
$this->adapter = $adapter;
} }
} }

View File

@@ -70,11 +70,8 @@ include 'views/foo-list.php';
<?php <?php
class FooModel class FooModel
{ {
protected $db; public function __construct(protected PDO $db)
public function __construct(PDO $db)
{ {
$this->db = $db;
} }
public function getAllFoos() { public function getAllFoos() {