【问题标题】:Slim 3 console execution for cron用于 cron 的 Slim 3 控制台执行
【发布时间】:2016-08-24 10:51:52
【问题描述】:

我正在尝试创建某种导入来移动数据库信息和转换数据。将来这个导入需要每天由 cron 执行。我想使用我编写的部分代码并重用一些模型和控制器。为此,我尝试通过命令行调用 Slim 3,但遇到了一些问题。

控制台命令:

 php cli.php import

我不知道如何正确处理argv

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
    });
}

如果我执行此操作,我会看到 404 Page not found 错误。

有什么路线吗?

【问题讨论】:

  • 我建议使用 symfony/console,它会有点独立,但我将它用于所有长时间运行的任务和 CLI 操作,因为它简单且易于插入。
  • 谢谢,我想但我想重用我所有的项目类来完成任务,并且 symfony/console 与 Slim PSR-7 不兼容。

标签: php cron console command-line-interface slim


【解决方案1】:

Slim 3 Framework 论坛中的某个人回答了这个问题并解决了我的问题。

我只是通过在代码中添加斜杠来修改它以避免添加调用。比如:

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

现在代码可以工作了,我可以从命令行调用它。

php cli.php import

这是因为 Slim 3 等待路由,并在我正在模拟的 REQUEST_URI 中添加一个斜杠,我可以执行代码。

【讨论】:

  • 我没有为我工作,你能把完整的文件发给我吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-27
  • 2015-08-13
  • 2013-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多