Add code samples

This commit is contained in:
Rob Landers 2021-02-12 18:26:51 +01:00
parent 459ccb0afc
commit ee7a7d19a1
No known key found for this signature in database
GPG Key ID: 97E1E91EBD47C889
4 changed files with 313 additions and 10 deletions

View File

@ -139,7 +139,7 @@ kubectl apply -f subscription.yaml
#### Example #### Example
{{< tabs Python Node>}} {{< tabs Python Node PHP>}}
{{% codetab %}} {{% codetab %}}
Create a file named `app1.py` and paste in the following: Create a file named `app1.py` and paste in the following:
@ -199,6 +199,37 @@ dapr --app-id app2 --app-port 3000 run node app2.js
``` ```
{{% /codetab %}} {{% /codetab %}}
{{% codetab %}}
Create a file named `app1.php` and paste in the following:
```php
<?php
require_once __DIR__.'/vendor/autoload.php';
$app = \Dapr\App::create();
$app->post('/dsstatus', function(
#[\Dapr\Attributes\FromBody]
\Dapr\PubSub\CloudEvent $cloudEvent,
\Psr\Log\LoggerInterface $logger
) {
$logger->alert('Received event: {event}', ['event' => $cloudEvent]);
return ['status' => 'SUCCESS'];
}
);
$app->start();
```
After creating `app1.php`, and with the [SDK installed](https://github.com/dapr/php-sdk/blob/main/docs/getting-started.md),
go ahead and start the app:
```bash
dapr --app-id app1 --app-port 3000 run -- php -S 0.0.0.0:3000 app1.php
```
{{% /codetab %}}
{{< /tabs >}} {{< /tabs >}}
### Programmatic subscriptions ### Programmatic subscriptions
@ -211,7 +242,7 @@ The Dapr instance calls into your app at startup and expect a JSON response for
#### Example #### Example
{{< tabs Python Node>}} {{< tabs Python Node PHP>}}
{{% codetab %}} {{% codetab %}}
```python ```python
@ -284,6 +315,38 @@ dapr --app-id app2 --app-port 3000 run node app2.js
``` ```
{{% /codetab %}} {{% /codetab %}}
{{% codetab %}}
Update `app1.php` with the following:
```php
<?php
require_once __DIR__.'/vendor/autoload.php';
$app = \Dapr\App::create(configure: fn(\DI\ContainerBuilder $builder) => $builder->addDefinitions(['dapr.subscriptions' => [
new \Dapr\PubSub\Subscription(pubsubname: 'pubsub', topic: 'deathStarStatus', route: '/dsstatus'),
]]));
$app->post('/dsstatus', function(
#[\Dapr\Attributes\FromBody]
\Dapr\PubSub\CloudEvent $cloudEvent,
\Psr\Log\LoggerInterface $logger
) {
$logger->alert('Received event: {event}', ['event' => $cloudEvent]);
return ['status' => 'SUCCESS'];
}
);
$app->start();
```
Run this app with:
```bash
dapr --app-id app1 --app-port 3000 run -- php -S 0.0.0.0:3000 app1.php
```
{{% /codetab %}}
{{< /tabs >}} {{< /tabs >}}
The `/dsstatus` endpoint matches the `route` defined in the subscriptions and this is where Dapr will send all topic messages to. The `/dsstatus` endpoint matches the `route` defined in the subscriptions and this is where Dapr will send all topic messages to.
@ -355,7 +418,7 @@ app.post('/dsstatus', (req, res) => {
## (Optional) Step 5: Publishing a topic with code ## (Optional) Step 5: Publishing a topic with code
{{< tabs Node>}} {{< tabs Node PHP>}}
{{% codetab %}} {{% codetab %}}
If you prefer publishing a topic using code, here is an example. If you prefer publishing a topic using code, here is an example.
@ -384,6 +447,32 @@ app.post('/publish', (req, res) => {
app.listen(process.env.PORT || port, () => console.log(`Listening on port ${port}!`)); app.listen(process.env.PORT || port, () => console.log(`Listening on port ${port}!`));
``` ```
{{% /codetab %}} {{% /codetab %}}
{{% codetab %}}
If you prefer publishing a topic using code, here is an example.
```php
<?php
require_once __DIR__.'/vendor/autoload.php';
$app = \Dapr\App::create();
$app->run(function(\DI\FactoryInterface $factory, \Psr\Log\LoggerInterface $logger) {
$publisher = $factory->make(\Dapr\PubSub\Publish::class, ['pubsub' => 'pubsub']);
$publisher->topic('deathStarStatus')->publish('operational');
$logger->alert('published!');
});
```
You can save this to `app2.php` and while `app1` is running in another terminal, execute:
```bash
dapr --app-id app2 run -- php app2.php
```
{{% /codetab %}}
{{< /tabs >}} {{< /tabs >}}
## Sending a custom CloudEvent ## Sending a custom CloudEvent

View File

@ -34,7 +34,7 @@ When non-Dapr subscribers use components such as Azure Service Bus, which native
Message TTL can be set in the metadata as part of the publishing request: Message TTL can be set in the metadata as part of the publishing request:
{{< tabs curl "Python SDK">}} {{< tabs curl "Python SDK" "PHP SDK">}}
{{% codetab %}} {{% codetab %}}
```bash ```bash
@ -64,6 +64,22 @@ with DaprClient() as d:
``` ```
{{% /codetab %}} {{% /codetab %}}
{{% codetab %}}
```php
<?php
require_once __DIR__.'/vendor/autoload.php';
$app = \Dapr\App::create();
$app->run(function(\DI\FactoryInterface $factory) {
$publisher = $factory->make(\Dapr\PubSub\Publish::class, ['pubsub' => 'pubsub']);
$publisher->topic('TOPIC_A')->publish('data', ['ttlInSeconds' => '120']);
});
```
{{% /codetab %}}
{{< /tabs >}} {{< /tabs >}}
See [this guide]({{< ref pubsub_api.md >}}) for a reference on the pub/sub API. See [this guide]({{< ref pubsub_api.md >}}) for a reference on the pub/sub API.

View File

@ -63,7 +63,7 @@ For a full API reference, go [here]({{< ref secrets_api.md >}}).
Once you have a secret store set up, you can call Dapr to get the secrets from your application code. Here are a few examples in different programming languages: Once you have a secret store set up, you can call Dapr to get the secrets from your application code. Here are a few examples in different programming languages:
{{< tabs "Go" "Javascript" "Python" "Rust" "C#" >}} {{< tabs "Go" "Javascript" "Python" "Rust" "C#" "PHP" >}}
{{% codetab %}} {{% codetab %}}
```Go ```Go
@ -151,6 +151,22 @@ Console.WriteLine(secret);
``` ```
{{% /codetab %}} {{% /codetab %}}
{{% codetab %}}
```php
<?php
require_once __DIR__.'/vendor/autoload.php';
$app = \Dapr\App::create();
$app->run(function(\Dapr\SecretManager $secretManager, \Psr\Log\LoggerInterface $logger) {
$secret = $secretManager->retrieve(secret_store: 'my-secret-store', name: 'my-secret');
$logger->alert('got secret: {secret}', ['secret' => $secret]);
});
```
{{% /codetab %}}
{{< /tabs >}} {{< /tabs >}}
## Related links ## Related links
@ -160,4 +176,4 @@ Console.WriteLine(secret);
- [Configure a secret store]({{<ref secret-stores-overview>}}) - [Configure a secret store]({{<ref secret-stores-overview>}})
- [Supported secrets]({{<ref secret-stores-overview>}}) - [Supported secrets]({{<ref secret-stores-overview>}})
- [Using secrets in components]({{<ref component-secrets>}}) - [Using secrets in components]({{<ref component-secrets>}})
- [Secret stores quickstart](https://github.com/dapr/quickstarts/tree/master/secretstore) - [Secret stores quickstart](https://github.com/dapr/quickstarts/tree/master/secretstore)

View File

@ -66,7 +66,7 @@ The following example shows how to a single key/value pair using the Dapr state
It is important to set an app-id, as the state keys are prefixed with this value. If you don't set it one is generated for you at runtime, and the next time you run the command a new one will be generated and you will no longer be able to access previously saved state. It is important to set an app-id, as the state keys are prefixed with this value. If you don't set it one is generated for you at runtime, and the next time you run the command a new one will be generated and you will no longer be able to access previously saved state.
{{% /alert %}} {{% /alert %}}
{{< tabs "HTTP API (Bash)" "HTTP API (PowerShell)" "Python SDK">}} {{< tabs "HTTP API (Bash)" "HTTP API (PowerShell)" "Python SDK" "PHP SDK">}}
{{% codetab %}} {{% codetab %}}
Begin by launching a Dapr sidecar: Begin by launching a Dapr sidecar:
@ -153,6 +153,45 @@ You are up and running! Both Dapr and your app logs will appear here.
{{% /codetab %}} {{% /codetab %}}
{{% codetab %}}
Save the following in `state-example.php`:
```php
<?php
require_once __DIR__.'/vendor/autoload.php';
$app = \Dapr\App::create();
$app->run(function(\Dapr\State\StateManager $stateManager, \Psr\Log\LoggerInterface $logger) {
$stateManager->save_state(store_name: 'statestore', item: new \Dapr\State\StateItem(
key: 'myFirstKey',
value: 'myFirstValue'
));
$logger->alert('State has been stored');
$data = $stateManager->load_state(store_name: 'statestore', key: 'myFirstKey')->value;
$logger->alert("Got value: {data}", ['data' => $data]);
});
```
Once saved run the following command to launch a Dapr sidecar and run the PHP application:
```bash
dapr --app-id myapp run -- php state-example.php
```
You should get an output similar to the following, which will show both the Dapr and app logs:
```md
✅ You're up and running! Both Dapr and your app logs will appear here.
== APP == [2021-02-12T16:30:11.078777+01:00] APP.ALERT: State has been stored [] []
== APP == [2021-02-12T16:30:11.082620+01:00] APP.ALERT: Got value: myFirstValue {"data":"myFirstValue"} []
```
{{% /codetab %}}
{{< /tabs >}} {{< /tabs >}}
@ -160,7 +199,7 @@ You are up and running! Both Dapr and your app logs will appear here.
The following example shows how to delete an item by using a key with the state management API: The following example shows how to delete an item by using a key with the state management API:
{{< tabs "HTTP API (Bash)" "HTTP API (PowerShell)" "Python SDK">}} {{< tabs "HTTP API (Bash)" "HTTP API (PowerShell)" "Python SDK" "PHP SDK">}}
{{% codetab %}} {{% codetab %}}
With the same dapr instance running from above run: With the same dapr instance running from above run:
@ -226,13 +265,58 @@ You're up and running! Both Dapr and your app logs will appear here.
``` ```
{{% /codetab %}} {{% /codetab %}}
{{% codetab %}}
Update `state-example.php` with the following contents:
```php
<?php
require_once __DIR__.'/vendor/autoload.php';
$app = \Dapr\App::create();
$app->run(function(\Dapr\State\StateManager $stateManager, \Psr\Log\LoggerInterface $logger) {
$stateManager->save_state(store_name: 'statestore', item: new \Dapr\State\StateItem(
key: 'myFirstKey',
value: 'myFirstValue'
));
$logger->alert('State has been stored');
$data = $stateManager->load_state(store_name: 'statestore', key: 'myFirstKey')->value;
$logger->alert("Got value: {data}", ['data' => $data]);
$stateManager->delete_keys(store_name: 'statestore', keys: ['myFirstKey']);
$data = $stateManager->load_state(store_name: 'statestore', key: 'myFirstKey')->value;
$logger->alert("Got value after delete: {data}", ['data' => $data]);
});
```
Now run it with:
```bash
dapr --app-id myapp run -- php state-example.php
```
You should see something similar the following output:
```md
✅ You're up and running! Both Dapr and your app logs will appear here.
== APP == [2021-02-12T16:38:00.839201+01:00] APP.ALERT: State has been stored [] []
== APP == [2021-02-12T16:38:00.841997+01:00] APP.ALERT: Got value: myFirstValue {"data":"myFirstValue"} []
== APP == [2021-02-12T16:38:00.845721+01:00] APP.ALERT: Got value after delete: {"data":null} []
```
{{% /codetab %}}
{{< /tabs >}} {{< /tabs >}}
## Step 4: Save and retrieve multiple states ## Step 4: Save and retrieve multiple states
Dapr also allows you to save and retrieve multiple states in the same call. Dapr also allows you to save and retrieve multiple states in the same call.
{{< tabs "HTTP API (Bash)" "HTTP API (PowerShell)" "Python SDK">}} {{< tabs "HTTP API (Bash)" "HTTP API (PowerShell)" "Python SDK" "PHP SDK">}}
{{% codetab %}} {{% codetab %}}
With the same dapr instance running from above save two key/value pairs into your statestore: With the same dapr instance running from above save two key/value pairs into your statestore:
@ -307,6 +391,53 @@ You're up and running! Both Dapr and your app logs will appear here.
{{% /codetab %}} {{% /codetab %}}
{{% codetab %}}
To batch load and save state with PHP, just create a "Plain Ole' PHP Object" (POPO) and annotate it with
the StateStore annotation.
Let's update our `state-example.php` file:
```php
<?php
require_once __DIR__.'/vendor/autoload.php';
#[\Dapr\State\Attributes\StateStore('statestore', \Dapr\consistency\EventualLastWrite::class)]
class MyState {
public string $key1 = 'value1';
public string $key2 = 'value2';
}
$app = \Dapr\App::create();
$app->run(function(\Dapr\State\StateManager $stateManager, \Psr\Log\LoggerInterface $logger) {
$obj = new MyState();
$stateManager->save_object(item: $obj);
$logger->alert('States have been stored');
$stateManager->load_object(into: $obj);
$logger->alert("Got value: {data}", ['data' => $obj]);
});
```
Run the app:
```bash
dapr --app-id myapp run -- php state-example.php
```
And see the following output:
```md
✅ You're up and running! Both Dapr and your app logs will appear here.
== APP == [2021-02-12T16:55:02.913801+01:00] APP.ALERT: States have been stored [] []
== APP == [2021-02-12T16:55:02.917850+01:00] APP.ALERT: Got value: [object MyState] {"data":{"MyState":{"key1":"value1","key2":"value2"}}} []
```
{{% /codetab %}}
{{< /tabs >}} {{< /tabs >}}
## Step 5: Perform state transactions ## Step 5: Perform state transactions
@ -315,7 +446,7 @@ You're up and running! Both Dapr and your app logs will appear here.
State transactions require a state store that supports multi-item transactions. Visit the [supported state stores page]({{< ref supported-state-stores >}}) page for a full list. Note that the default Redis container created in a self-hosted environment supports them. State transactions require a state store that supports multi-item transactions. Visit the [supported state stores page]({{< ref supported-state-stores >}}) page for a full list. Note that the default Redis container created in a self-hosted environment supports them.
{{% /alert %}} {{% /alert %}}
{{< tabs "HTTP API (Bash)" "HTTP API (PowerShell)" "Python SDK" >}} {{< tabs "HTTP API (Bash)" "HTTP API (PowerShell)" "Python SDK" "PHP SDK">}}
{{% codetab %}} {{% codetab %}}
With the same dapr instance running from above perform two state transactions: With the same dapr instance running from above perform two state transactions:
@ -400,6 +531,57 @@ You're up and running! Both Dapr and your app logs will appear here.
{{% /codetab %}} {{% /codetab %}}
{{% codetab %}}
Transactional state is supported by extending `TransactionalState` base object which hooks into your
object via setters and getters to provide a transaction. Before we created our own transactional object,
but now we'll ask the Dependency Injection framework to build one for us.
Let's modify our `state-example.php` file again:
```php
<?php
require_once __DIR__.'/vendor/autoload.php';
#[\Dapr\State\Attributes\StateStore('statestore', \Dapr\consistency\EventualLastWrite::class)]
class MyState extends \Dapr\State\TransactionalState {
public string $key1 = 'value1';
public string $key2 = 'value2';
}
$app = \Dapr\App::create();
$app->run(function(MyState $obj, \Psr\Log\LoggerInterface $logger, \Dapr\State\StateManager $stateManager) {
$obj->begin();
$obj->key1 = 'hello world';
$obj->key2 = 'value3';
$obj->commit();
$logger->alert('Transaction committed!');
// begin a new transaction which reloads from the store
$obj->begin();
$logger->alert("Got value: {key1}, {key2}", ['key1' => $obj->key1, 'key2' => $obj->key2]);
});
```
Run the application:
```bash
dapr --app-id myapp run -- php state-example.php
```
Observe the following output:
```md
✅ You're up and running! Both Dapr and your app logs will appear here.
== APP == [2021-02-12T17:10:06.837110+01:00] APP.ALERT: Transaction committed! [] []
== APP == [2021-02-12T17:10:06.840857+01:00] APP.ALERT: Got value: hello world, value3 {"key1":"hello world","key2":"value3"} []
```
{{% /codetab %}}
{{< /tabs >}} {{< /tabs >}}
## Next steps ## Next steps