duanqian6982 2017-10-14 21:02
浏览 65

在不使用HTTP / Console Kernel的情况下访问Laravel服务的最低代码是什么?

I need to access to my app services in a simple php script. I don't want to create a HTTP/Console kernel. If the following is the content test.php file in the app root, what else should I call to make it working?

require_once __DIR__ . "/vendor/autoload.php"; //composer
$app = new Illuminate\Foundation\Application(realpath(__DIR__));
$app->boot(); // not sure about this
$app->make('db')->table('user')->get()->toArray();

Currently I get the following error:

PHP Fatal error:  Uncaught ReflectionException: Class db does not exist in foo\vendor\laravel\framework\src\Illuminate\Container\Container.php:752
Fatal error: Uncaught ReflectionException: Class db does not exist in foo\vendor\laravel\framework\src\Illuminate\Container\Container.php:752
  • 写回答

1条回答 默认 最新

  • douxiong2001 2017-10-15 00:20
    关注

    After checking the source code it's clear that the Application class does not load all classes defined in the config/app.php file and either you have bootstrap it yourself of running bootstrap function of build-in kernel. So, If you create a php file with the following lines you can access all app dependencies without bothering creating artisan command to do your snippet codes directly in phpstorm.

    require_once __DIR__ . "/vendor/autoload.php"; //composer
    $app = new Illuminate\Foundation\Application(realpath(__DIR__));
    
    // http Kernel yet have to be registered, perhaps a bad design issue.
    $app->singleton(
      Illuminate\Contracts\Http\Kernel::class,
      App\Http\Kernel::class
    );
    
    $app->singleton(
      Illuminate\Contracts\Console\Kernel::class,
      App\Console\Kernel::class
    );
    // optional
    $app->singleton(
      Illuminate\Contracts\Debug\ExceptionHandler::class,
      App\Exceptions\Handler::class
    );
    
    $kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
    $kernel->bootstrap();
    
    // and playground is ready 
    $users= $app->make('db')->table('user')->get()->toArray();
    

    or

    require_once __DIR__ . "/vendor/autoload.php";
    $app = include_once __DIR__.'/bootstrap/app.php';
    $kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
    $kernel->bootstrap();
    
    dd(app('db')->table('user')->count());
    
    评论

报告相同问题?

悬赏问题

  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接