Skip to content

Commit

Permalink
Enable dependency injection in check constructors
Browse files Browse the repository at this point in the history
  • Loading branch information
dennis-koster committed Feb 2, 2023
1 parent dbe8b39 commit 5fc13a3
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/Checks/Check.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Cron\CronExpression;
use Illuminate\Console\Scheduling\ManagesFrequencies;
use Illuminate\Container\Container;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Str;
use Spatie\Health\Enums\Status;
Expand All @@ -20,13 +21,13 @@ abstract class Check

protected bool $shouldRun = true;

final public function __construct()
public function __construct()
{
}

public static function new(): static
{
$instance = new static();
$instance = Container::getInstance()->make(static::class);

$instance->everyMinute();

Expand Down
10 changes: 10 additions & 0 deletions tests/Checks/DependencyInjectionCheckTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

use Psr\Log\LoggerInterface;
use Spatie\Health\Tests\TestClasses\DependencyInjectionCheck;

it('will use dependency injection to resolve constructor arguments', function () {
$check = DependencyInjectionCheck::new();

expect($check->getLogger())->toBeInstanceOf(LoggerInterface::class);
});
36 changes: 36 additions & 0 deletions tests/TestClasses/DependencyInjectionCheck.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

declare(strict_types=1);

namespace Spatie\Health\Tests\TestClasses;

use Psr\Log\LoggerInterface;
use Spatie\Health\Checks\Check;
use Spatie\Health\Checks\Result;
use Spatie\Health\Enums\Status;

class DependencyInjectionCheck extends Check
{
protected LoggerInterface $logger;

public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;

parent::__construct();
}

public function run(): Result
{
$this->logger->info('Dependency injection worked');

return new Result(
Status::ok(),
);
}

public function getLogger(): LoggerInterface
{
return $this->logger;
}
}

0 comments on commit 5fc13a3

Please sign in to comment.