본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

앱

원문 보기 위키 갱신

앱 (App)

PHP에는 기본 라우터가 없어요. 그래서 \Dapr\App 클래스가 제공돼요. 이 클래스는 내부적으로 Nikic의 FastRoute를 사용해요. 하지만 원하는 라우터나 프레임워크를 자유롭게 사용해도 돼요. App 클래스의 add_dapr_routes() 메서드를 확인해서 액터와 구독이 어떻게 구현되는지 살펴보세요. 모든 앱은 App::create()로 시작해야 해요. 이 메서드는 두 개의 파라미터를 받는데, 첫 번째는 기존 DI 컨테이너(있다면)이고 두 번째는 ContainerBuilder에 연결해서 자신의 구성을 추가하는 콜백이에요. 그다음 라우트를 정의하고 $app->start()를 호출해서 현재 요청에서 라우트를 실행해야 해요.

<?php
// app.php

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

$app = \Dapr\App::create(configure: fn(\DI\ContainerBuilder $builder) => $builder->addDefinitions('config.php'));

// add a controller for GET /test/{id} that returns the id
$app->get('/test/{id}', fn(string $id) => $id);

$app->start();

출처: Dapr 문서

본문

컨트롤러에서 반환하기

컨트롤러에서 무엇이든 반환할 수 있고, json 객체로 직렬화돼요. 또한 Psr Response 객체를 요청해서 대신 반환할 수도 있는데, 이렇게 하면 헤더를 맞춤 설정하고 전체 응답을 제어할 수 있어요:

<?php
$app = \Dapr\App::create(configure: fn(\DI\ContainerBuilder $builder) => $builder->addDefinitions('config.php'));

// add a controller for GET /test/{id} that returns the id
$app->get('/test/{id}',
fn(
string $id,
\Psr\Http\Message\ResponseInterface $response,
\Nyholm\Psr7\Factory\Psr17Factory $factory) => $response->withBody($factory->createStream($id)));

$app->start();

앱을 클라이언트로 사용하기

Dapr을 클라이언트로만 사용하고 싶다면(예: 기존 코드에서) $app->run()을 호출할 수 있어요. 이런 경우에는 보통 커스텀 구성이 필요 없지만, 특히 프로덕션에서는 컴파일된 DI 컨테이너를 사용하고 싶을 수 있어요:

<?php
// app.php

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

$app = \Dapr\App::create(configure: fn(\DI\ContainerBuilder $builder) => $builder->enableCompilation(__DIR__));
$result = $app->run(fn(\Dapr\DaprClient $client) => $client->get('/invoke/other-app/method/my-method'));

다른 프레임워크에서 사용하기

DaprClient 객체가 제공돼요. 사실 App 객체가 사용하는 모든 설탕(sugar)은 DaprClient 위에 구축돼 있어요.

<?php

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

$clientBuilder = \Dapr\Client\DaprClient::clientBuilder();

// you can customize (de)serialization or comment out to use the default JSON serializers.
$clientBuilder = $clientBuilder->withSerializationConfig($yourSerializer)->withDeserializationConfig($yourDeserializer);

// you can also pass it a logger
$clientBuilder = $clientBuilder->withLogger($myLogger);

// and change the url of the sidecar, for example, using https
$clientBuilder = $clientBuilder->useHttpClient('https://localhost:3800')

그 전에 호출할 수 있는 몇 가지 함수가 있어요.

더 알아보기 (Learn more)