我目前正在构建一个应用程序,该应用程序使用Slim v4
和PHP-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来调用Timed通知文件,或者一个单独的具有TimedNotification实例化的文件,如0 23 * * * /my/dir/mycrons && php timednotifications.php
有没有一种行之有效的方法来实现这一点,或者我必须在一个文件中构建整个应用程序才能运行CRON?
要自动连接依赖项,必须使用DI容器。
示例:
<?php
use DIContainerBuilder;
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控制台将是";标准";路要走。
文件:binconsole.php
<?php
use PsrContainerContainerInterface;
use SymfonyComponentConsoleApplication;
use SymfonyComponentConsoleInputArgvInput;
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();