$ php composer.phar require vlucas/phpdotenv .env DEBUG=1 DISPLAY_ERROR=1 DATABASE_HOST=localhost DATABASE_POST=3306 DATABASE_NAME=dbname DATABASE_USER=user DATABASE_PASS=password DATABASE_CHARSET=utf8 public/index.php if (is_readable(__DIR__ . '/../.env')) { $dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/../'); $dotenv->load(); } $_ENV もしくは $_SERVER で使用できるようになりますが、getenv では使用できません。 if (is_readable(__DIR__ . '/../.env')) { $repository = Dotenv\Repository\RepositoryBuilder::createWithNoAdapters() ->addAdapter(Dotenv\Repository\Adapter\EnvConstAdapter::class) ->addWriter(Dotenv\Repository\Adapter\PutenvAdapter::class) ->immutable() ->make(); $dotenv = Dotenv\Dotenv::create($repository, __DIR__ . '/../'); $dotenv->load(); } このようにすると $_ENV もしくは getenv で使用できるようになります。 app/settings.php 'db' => [ 'host' => getenv('DATABASE_HOST'), 'port' => getenv('DATABASE_POST'), 'dbname' => getenv('DATABASE_NAME'), 'user' => getenv('DATABASE_USER'), 'password' => getenv('DATABASE_PASS'), 'charset' => getenv('DATABASE_CHARSET'), 'options' => [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, ], ], app/dependencies.php $containerBuilder->addDefinitions([ PDO::class => function (ContainerInterface $c) { $settings = $c->get('settings')['db']; $dsn = 'mysql:host=' . $settings['host'] . ';' . 'port=' . $settings['port'] . ';' . 'dbname=' . $settings['dbname'] . ';' . 'charset=' . $settings['charset']; return new PDO($dsn, $settings['user'], $settings['password'], $settings['options']); }, ]); src/Application/Actions/Action.php /** * @var POD */ protected $db; /** * @param LoggerInterface $logger * @param Twig $view * @param PDO $db */ public function __construct( LoggerInterface $logger, Twig $twig, \PDO $db ) { $this->logger = $logger; $this->view = $twig; $this->db = $db; } src/Application/Actions/User/UserAction.php /** * @param LoggerInterface $logger * @param Twig $view * @param PDO $db * @param UserRepository $userRepository */ public function __construct(LoggerInterface $logger, Twig $view, \PDO $db, UserRepository $userRepository) { parent::__construct($logger, $view, $db); $this->userRepository = $userRepository; } src/Application/Actions/User/ListUsersAction.php $sql = 'SELECT * FROM test'; $sth = $this->db->prepare($sql); $sth->execute(); $row = $sth->fetch(); |