PHP

Dapr提供了帮助开发 PHP 应用程序各种包。 你可以使用他们来创建 PHP 客户端、服务器和 virtual actors。

设置

先决条件

可选条件

初始化您的项目

在您想要创建服务的目录中,运行 composer init 并确认命令执行。 安装 dapr/php-sdk 和您可能希望使用的其他依赖项。

配置服务

创建一个 config.php ,复制下面的内容:

  1. <?php
  2. use Dapr\Actors\Generators\ProxyFactory;
  3. use Dapr\Middleware\Defaults\{Response\ApplicationJson,Tracing};
  4. use Psr\Log\LogLevel;
  5. use function DI\{env,get};
  6. return [
  7. // set the log level
  8. 'dapr.log.level' => LogLevel::WARNING,
  9. // Generate a new proxy on each request - recommended for development
  10. 'dapr.actors.proxy.generation' => ProxyFactory::GENERATED,
  11. // put any subscriptions here
  12. 'dapr.subscriptions' => [],
  13. // if this service will be hosting any actors, add them here
  14. 'dapr.actors' => [],
  15. // if this service will be hosting any actors, configure how long until dapr should consider an actor idle
  16. 'dapr.actors.idle_timeout' => null,
  17. // if this service will be hosting any actors, configure how often dapr will check for idle actors
  18. 'dapr.actors.scan_interval' => null,
  19. // if this service will be hosting any actors, configure how long dapr will wait for an actor to finish during drains
  20. 'dapr.actors.drain_timeout' => null,
  21. // if this service will be hosting any actors, configure if dapr should wait for an actor to finish
  22. 'dapr.actors.drain_enabled' => null,
  23. // you shouldn't have to change this, but the setting is here if you need to
  24. 'dapr.port' => env('DAPR_HTTP_PORT', '3500'),
  25. // add any custom serialization routines here
  26. 'dapr.serializers.custom' => [],
  27. // add any custom deserialization routines here
  28. 'dapr.deserializers.custom' => [],
  29. // the following has no effect, as it is the default middlewares and processed in order specified
  30. 'dapr.http.middleware.request' => [get(Tracing::class)],
  31. 'dapr.http.middleware.response' => [get(ApplicationJson::class), get(Tracing::class)],
  32. ];

创建一个服务

修改index.php,内容如下:

  1. <?php
  2. require_once __DIR__.'/vendor/autoload.php';
  3. use Dapr\App;
  4. $app = App::create(configure: fn(\DI\ContainerBuilder $builder) => $builder->addDefinitions(__DIR__ . '/config.php'));
  5. $app->get('/hello/{name}', function(string $name) {
  6. return ['hello' => $name];
  7. });
  8. $app->start();

试试吧

dapr init初始化dapr,然后用dapr run -a dev -p 3000-php -S 0.0.0.0:3000启动项目。

现在,您可以打开网络浏览器访问http://localhost:3000/ hello/world用您的名字,宠物的名字或您想要的任何名称替换world

恭喜,你已经建立了你的Dapr 服务! 我很高兴看到您会怎么做!

更多信息