我一直在使用 symfony/console 来创建命令并像这样注册它们,一切正常:
垃圾箱/控制台:
#!/usr/bin/env php
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use App\Commands\LocalitiesCommand;
use Symfony\Component\Console\Application;
$app = new Application();
$app->add(new LocalitiesCommand(new LocalitiesGenerator()));
$app->run();
Run Code Online (Sandbox Code Playgroud)
src/Commands/LocalitiesCommand.php:
<?php
declare(strict_types=1);
namespace App\Commands;
use App\LocalitiesGenerator;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
final class LocalitiesCommand extends Command
{
protected static $defaultName = 'app:generate-localities';
public function __construct(private LocalitiesGenerator $localitiesGenerator)
{
parent::__construct();
}
protected function configure(): void
{
$this
->setDescription('Generate localities.json file')
->setHelp('No arguments needed.');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->localitiesGenerator->generateJsonLocalities();
$output->writeln("File localities.json generated!"); …Run Code Online (Sandbox Code Playgroud) I started a project using composer and donlowaded the package vlucas/phpdotenv. I would like to call the $_ENV['name'] for example in my whole project without needing to instantiate the dot env in every class like that:
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();
Run Code Online (Sandbox Code Playgroud)
How can I achieve that like a laravel framework does for example?
Another question is I tough I needed to import my autoload require __DIR__.'/../vendor/autoload.php'; in order to call use Dotenv\Dotenv;...
我如何在类中使用 Dotenv 而不需要自动加载?
编辑添加index.php:
<?php
use Dotenv\Dotenv;
require …Run Code Online (Sandbox Code Playgroud)