2

I'm trying to create some kind of import to move database info and transform data. In the future this import needs to be executed by cron every day. I want to use part of my written code and reuse some models and controllers. To do this I'm trying to call Slim 3 through the command line, but I have some problems.

console command:

 php cli.php import

I don't know how to process argv correctly.

cli.php:

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

if (PHP_SAPI == 'cli') {
    $argv = $GLOBALS['argv'];
    array_shift($argv);

    $pathInfo       = implode('/', $argv);

    $env = \Slim\Http\Environment::mock(['PATH_INFO' => $pathInfo]);

    $settings = require __DIR__ . '/app/config/settings.php'; // here are return ['settings'=>'']

    //I try adding here path_info but this is wrong, I'm sure
    $settings['environment'] = $env; 

    $app = new \Slim\App($settings);

    $container = $app->getContainer();
    $container['errorHandler'] = function ($c) {
        return function ($request, $response, $exception) use ($c) {
             //this is wrong, i'm not with http
             return $c['response']->withStatus(500)
                  ->withHeader('Content-Type', 'text/text')
                  ->write('Something went wrong!');
        };
    };

    $container['notFoundHandler'] = function ($c) {
        //this is wrong, i'm not with http
        return function ($request, $response) use ($c) {
            return $c['response']
                ->withStatus(404)
                ->withHeader('Content-Type', 'text/text')
                ->write('Not Found');
        };
    };

    $app->map(['GET'], 'import', function() {
       // do import calling Actions or Controllers
    });
}

If I execute this I see a 404 Page not found error.

Any directions?

Community
  • 1
  • 1
Mork
  • 365
  • 5
  • 18
  • I would suggest using symfony/console it would be a little separate but I usei t for all my long running tasks and CLI operations as its just simple and easy to plug in. – clonerworks May 03 '16 at 03:20
  • Thanks, I thought but i want to reuse all my project class to do the task and _symfony/console_ is not compatible with Slim PSR-7. – Mork May 03 '16 at 20:26

1 Answers1

4

Someone in Slim 3 Framework discussion forums answered the question and solved my problem.

I just modified it by adding a slash in the code to avoid adding a call. Something like:

$env = \Slim\Http\Environment::mock(['REQUEST_URI' => '/' . $pathInfo]);

Now the code works and I can call it from the command line.

php cli.php import

This is because Slim 3 waits for a route, and adds a slash to REQUEST_URI I'm emulating and I can execute code.

Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
Mork
  • 365
  • 5
  • 18