我如何 运行 使用自动连接的 cron 类

How would I run a cron using auto-wired classes

我目前正在构建一个使用 Slim v4PHP-DI 自动连接依赖项的应用程序。这太棒了,除了我需要构建一个利用一些自动连接的 类 的 CRON。这是我的例子:

class NotificationService
{

    private $notification;

    public function __construct( NotificationFactory $notificationFactory )
    {
        $this->notification = $notificationFactory;
    }
}

在这种情况下,通知服务自动连接以使用通知工厂,这很棒。但我需要创建一个利用 NotificationService 发送通知的 CRON:

class TimedNotification
{

    private $notification;

    public function __construct( NotificationService $notificationService )
    {
         $this->notification = $notificationService;
    }


    public function sendNotification(): bool
    {
        $sent = $this->notification->sendMessage( 'This message is a test.' );
        return $sent;

    }

}

// Separate File
$timedNotification = new TimedNotification();
$timedNotification->sendMessage();

我希望能够使用 CRON 来调用定时通知文件,或具有 TimedNotification 实例化的单独文件,例如 0 23 * * * /my/dir/mycrons && php timednotifications.php

是否有执行此操作的可靠方法,或者我是否必须将整个应用程序构建到 运行 CRON 的文件中?

要自动装配依赖项,您必须使用 DI 容器。

示例:

<?php

use DI\ContainerBuilder;

require_once __DIR__ . '/../vendor/autoload.php';

class NotificationService
{
    public function sendMessage(string $message): bool
    {
        echo $message . "\n";

        return true;
    }
}

class TimedNotification
{
    private $notification;

    public function __construct(NotificationService $notificationService)
    {
        $this->notification = $notificationService;
    }

    public function sendNotification(): bool
    {
        $sent = $this->notification->sendMessage('This message is a test.');

        return $sent;
    }

}

$containerBuilder = new ContainerBuilder();

// Add container definitions
//$containerBuilder->addDefinitions(...);

// Build PHP-DI Container instance
$container = $containerBuilder->build();

// Separate File
$timedNotification = $container->get(TimedNotification::class);
$timedNotification->sendNotification();

输出:

This message is a test.

在现实世界的应用程序中,Symfony 控制台将是“标准”方式。

文件:bin\console.php

<?php

use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\ArgvInput;

require_once __DIR__ . '/../vendor/autoload.php';

$env = (new ArgvInput())->getParameterOption(['--env', '-e'], 'development');

if ($env) {
    $_ENV['APP_ENV'] = $env;
}

/** @var ContainerInterface $container */
$container = (require __DIR__ . '/../config/bootstrap.php')->getContainer();

$application = $container->get(Application::class);

// Add custom commands
// See: https://symfony.com/doc/current/console.html#creating-a-command

$application->add($container->get(MyCustomCommand::class));
$application->add($container->get(MySecondCommand::class));
// ...

$application->run();