PHP code example of govorun / framework

1. Go to this page and download the library: Download govorun/framework library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

govorun / framework example snippets


$app = new Application(dirname(__DIR__));

use Govorun\Routing\Route;

Route::command('start', StartController::class);
Route::phrase('привет', HelloController::class);
Route::pattern('/^\d+$/', NumberController::class);
Route::action('confirm', ConfirmController::class);
Route::event('member_joined', WelcomeController::class);
Route::media('photo', PhotoController::class);
Route::location(LocationController::class);
Route::contact(ContactController::class);
Route::referral('promo', PromoController::class);
Route::fallback(FallbackController::class);

Route::middleware(AuthMiddleware::class, function () {
    Route::command('admin', AdminController::class);
});

Route::phrase('меню', function () {
    Route::phrase('цены', PriceController::class);
    Route::phrase('контакты', ContactInfoController::class);
});

Route::phrase('привет', HelloController::class)
    ->alias(['здравствуйте', 'добрый день']);

use Govorun\Routing\Controller;

class StartController extends Controller
{
    public function handle(): void
    {
        $name = $this->message->user->firstName;
        $this->reply("Привет, {$name}!");
    }
}

use Govorun\Messaging\Message;

$msg = Message::make('Текст')
    ->keyboard($keyboard)
    ->parseMode('HTML');

use Govorun\Messaging\Button;
use Govorun\Messaging\Keyboard;

// Inline
Keyboard::make()->buttons([
    [
        Button::make('Текст')->action('confirm', ['id' => 42]),
        Button::make('Ссылка')->url('https://example.com'),
    ],
    [Button::make('Новый ряд')->action('continue')],
]);

// Reply (с fluent-флагами)
Keyboard::reply()
    ->resize()
    ->oneTime()
    ->buttons([
        [Button::make('Контакт')->requestContact()],
        [Button::make('Локация')->requestLocation()],
    ]);

// Снять клавиатуру
Keyboard::remove();

use Govorun\Messaging\Media;

Media::photo('https://example.com/img.jpg')->caption('Описание');
Media::document('https://example.com/file.pdf');
Media::video('https://example.com/clip.mp4');
Media::audio('https://example.com/track.mp3');
Media::voice('https://example.com/voice.ogg');
Media::animation('https://example.com/anim.gif');

Button::make('Текст')
    ->action('callback_action', ['key' => 'value'])
    ->url('https://...')
    ->requestContact()
    ->requestLocation();

use Govorun\State\Flow;
use Govorun\State\Step;
use Govorun\Messaging\Keyboard;
use Govorun\Messaging\Button;
use Govorun\Messaging\IncomingMessage;

class OrderFlow extends Flow
{
    protected array $steps = ['product', 'quantity', 'confirm'];
    protected array $interruptCommands = ['/start', '/cancel'];
    protected bool $interruptOnEvent = true;

    public function productStep(Step $step): void
    {
        $step->ask('Какой товар вас интересует?');

        $step->receive(function (IncomingMessage $msg) {
            if ($this->validator($msg->text)->;
        $qty = $this->state->get('quantity');

        $step->ask(
            "Заказ: {$product} x {$qty}. Подтвердить?",
            Keyboard::make()->buttons([[
                Button::make('Да')->action('yes'),
                Button::make('Нет')->action('no'),
            ]]),
        );

        $step->receive(function (IncomingMessage $msg) {
            if ($msg->action === 'yes') {
                $this->reply('Заказ принят!');
            }
            $this->nextStep(); // обязателен — завершает flow и чистит state
        });
    }

    public function onComplete(): void {}
    public function onCancel(): void { $this->reply('Заказ отменён.'); }
}

$step->ask(
    string|OutgoingMessage $message,
    Closure|Keyboard|null  $keyboard = null,  // прямой Keyboard или Closure-билдер
);

$step->receive(Closure $callback);  // function (IncomingMessage $msg): void

interface StateStorage
{
    public function get(string $chatId, string $driver): ?array;
    public function set(string $chatId, string $driver, array $data): void;
    public function delete(string $chatId, string $driver): void;
}

return [
    'payment' => [
        'base_url' => 'https://api.payment.com/v1',
        'default_headers' => ['Accept' => 'application/json'],
        'auth' => ['type' => 'bearer', 'token' => env('PAYMENT_TOKEN')],
    ],
];

$response = $this->http()->connection('payment')->post('/charge', [
    'json' => ['amount' => 100, 'currency' => 'RUB'],
]);

if ($response->successful()) {
    $payment = $response->json();
}

use Govorun\Http\ApiClient;

class PaymentClient extends ApiClient
{
    protected int $timeout = 10;
    protected int $retries = 2;

    public function baseUrl(): string
    {
        return 'https://api.payment.com/v1';
    }

    public function headers(): array
    {
        return ['Authorization' => 'Bearer ' . env('PAYMENT_KEY')];
    }
}

use Govorun\Support\Validator;

$error = Validator::make($msg->text)
    -> — null если ок

if ($error !== null) {
    $this->reply($error);
    return;
}

if ($this->validator($msg->text)->

use Govorun\Routing\Middleware;
use Govorun\Messaging\IncomingMessage;

class LogMiddleware implements Middleware
{
    public function handle(IncomingMessage $message, \Closure $next): void
    {
        logger()->info("Message from {$message->user->id}: {$message->text}");
        $next($message);
    }
}

use Govorun\Foundation\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void { /* привязки контейнера */ }
    public function boot(): void { /* после регистрации всех провайдеров */ }
}

'providers' => [
    App\Providers\AppServiceProvider::class,
],
bash
php govorun webhook:install

HTTP POST → public/index.php → Application::handleWebhook()
  1. loadEnvironment()             — загрузка .env
  2. loadConfiguration()           — загрузка config/*.php
  3. registerCoreProviders()       — EventServiceProvider, LogServiceProvider, StateServiceProvider
  4. registerConfiguredProviders() — провайдеры из config('app.providers')
  5. boot()                        — boot всех провайдеров
  6. loadRoutes()                  — routes/messenger.php
  7. resolveDriverName()           — драйвер из URL
  8. resolveDriver()               — экземпляр драйвера
  9. verifyWebhook()               — проверка подписи
 10. parseUpdate()                 — парсинг в IncomingMessage
 11. FlowHandler::handle()         — возобновление активного Flow (если есть)
 12. Router::dispatch()            — диспатч в Controller или Flow-старт