mirror of
https://github.com/codeguy/php-the-right-way.git
synced 2025-08-05 13:37:25 +02:00
Use PHP constructor property promotion
This commit is contained in:
@@ -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
|
||||||
|
@@ -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;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -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() {
|
||||||
|
Reference in New Issue
Block a user