How to get config variables in a independant php cron script (expressive)?




I made a simple expressive project that use authentication, form, database…
I need to create a cron script (cli) that will connect to the database and send some email.

I would like to use the same config file (db key in local.php in my case) for the credentials… For database, i will simply request with raw PDO or use my existing models if is possible.

What is the good approach for loading the config in a independent php file? (ex: my-cron-script.php)



There are several ways to load it.

// Load the one config file
$config = require 'config/autoload/local.php';

// Load the entire config
$config = require 'config/config.php';

// Or even better, load the container and grab the database service
$container = require 'config/container.php';
$db = $container->get(Zend\Db\Adapter\AdapterInterface::class);


Thanks! i’ll test it!


I have a different approach where I consider the index.php as the single source of truth for bootstrapping my app. So I edited it slightly to have something like:

// we only run the application if this file was NOT included (otherwise, the file was included to access misc functions)
if (realpath(__FILE__) === realpath($_SERVER['SCRIPT_FILENAME'])) {

And then in each of my “command” files, I can simply include index.php, like so:

#! /usr/bin/env php

 * A script to show missing files on disk and non-needed files on disk
use Application\Model\Card;
use Application\Utility;

require_once __DIR__ . '/../htdocs/index.php';

$filesInDb = _em()->getRepository(Card::class)->getFilenames();
// ...

Of course, it might be considered less “clean”, because I create an $app that will never be used, and we could probably argue that config/container.php should be the single source of truth. But I like the guarantee it gives me that it will always be bootstrapped exactly the same way (composer libs, current directory).

You can see an example of that in a real project here and there.