PHP code example of kode / core

1. Go to this page and download the library: Download kode/core 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/ */

    

kode / core example snippets



Kode\Core\App;
use Kode\Core\Config\Config;
use Kode\Core\Provider\ServiceProvider;

// 1) 业务服务
final class Greeter
{
    public function __construct(private string $name) {}
    public function hello(): string { return "Hello, {$this->name}!"; }
}

// 2) 服务提供者
final class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $name = $this->container->make(Config::class)->get('app.name', 'Kode');
        $this->container->singleton(Greeter::class, fn() => new Greeter($name));
    }
}

// 3) 一行启动
$app = App::boot([
    'base_path'   => __DIR__,
    'config_path' => __DIR__ . '/config',   // 目录下的 *.php 自动加载为配置
    'providers'   => [AppServiceProvider::class],
    'runtime'     => ['fiber'],             // 启用命令:叠加协程运行时
]);

echo $app->make(Greeter::class)->hello();   // Hello, Kode!
echo $app->config('app.name');              // Kode

app();                 // 返回已启动的 App 实例(等价于 App::getInstance())
app(Greeter::class);   // 等价于 $app->make(Greeter::class)
config('app.name');    // 读配置(等价于 $app->config('app.name'))
runtime();             // 返回 Runtime 实例(等价于 $app->runtime)

// App 便捷方法
App::VERSION;          // 当前版本号,如 '1.1.0'(与 git tag 保持一致)
$app->version();       // 等价于 App::VERSION
$app->has(Greeter::class);            // 容器中是否存在该绑定
$app->call(fn (Greeter $g) => $g->hello());  // 以 DI 自动注入方式调用回调
$app->isCli();                        // 是否运行在 CLI / PHPDBG 下
$app->runningInConsole();             // 等价于 isCli()(语义化别名)
$app->environment();                  // 返回当前环境(app.env,默认 'production')
$app->environment('testing');         // 当前是否为 testing → true / false
$app->basePath();                     // 应用基路径(boot 的 base_path,缺省 getcwd())
$app->basePath('config/app.php');     // 基路径拼接相对路径
$app->path();                         // 应用源码路径(basePath/src)
$app->enableRuntime('process');       // 链式启用运行时(等价于 $app->runtime->enable())

use Kode\Core\Facade;

// 1) 定义门面:id() 返回容器中服务的标识
final class Cache extends Facade
{
    protected static function id(): string
    {
        return CacheInterface::class;
    }
}

// 2) 容器里绑定该服务(在 ServiceProvider 或 boot 后均可)
app()->container->singleton(CacheInterface::class, fn () => new RedisCache());

// 3) 静态调用,等价于 app(CacheInterface::class)->get('k')
Cache::get('k');

> $app->enableFacadeContextSafe();        // 开启(协程隔离)
> $app->enableFacadeContextSafe(false);    // 关闭
> \Kode\Core\Facade::enableContextSafeForAll(); // 为已解析的门面批量开启
> 

// 执行单元级上下文读写(协程/线程间自动隔离)
ctx()->set('tenant_id', 42);
ctx()->get('tenant_id');                 // 42
ctx()->push('tags', 'vip');              // 数组型值追加

// 作用域隔离:回调结束自动回滚,避免污染外层上下文
ctx()->transaction(fn () => ctx()->set('tmp', 1));

// 分布式链路追踪:开启 → 导出 HTTP 头 → 在下游服务还原
$traceId = ctx()->startTrace();          // 自动生成合规 32 位十六进制 trace_id
$headers = ctx()->toHeaders();           // ['traceparent'=>..., 'X-Context-Trace-Id'=>..., ...]
ctx()->fromHeaders($incomingHeaders);    // 在消费者侧恢复链路(优先 W3C 标准头)

// 启动完成后执行(应用已启动则注册即立即执行;否则在启动序列末尾触发)
$app->booted(function (App $app): void {
    // 依赖已就绪,可做后处理
});

// 应用终止(PHP shutdown)时执行(App::boot() 已自动注册 register_shutdown_function)
$app->terminating(function (): void {
    // 清理资源、关闭连接等
});
// 也可在测试中手动触发: $app->callTerminatingCallbacks()

// 1) 事件总线:组件间解耦通信
$app->listen('order.created', fn (string $id) => /* ... */);
$results = $app->dispatch('order.created', $orderId); // 按注册顺序调用,返回各监听器返回值数组
$app->hasListeners('order.created');                  // 是否有监听器
$app->forget('order.created');                        // 清空该事件监听器

// 2) 维护模式(文件标记,常用于发布/紧急停机)
$app->isDownForMaintenance();   // 是否处于维护模式
$app->down('升级中');           // 进入维护模式(写入 storage/framework/down)
$app->up();                     // 退出维护模式

// 3) 运行环境判定
$app->runningUnitTests();       // 是否单元测试环境(PHPUnit / APP_ENV=testing)

// 容器由 kode/core 在启动时创建(Kode\DI\Container),可通过 App 取得
$container = $app->container;

// 绑定抽象到实现
$container->bind(LoggerInterface::class, FileLogger::class);

// 单例
$container->singleton(Greeter::class, fn($c) => new Greeter($c->make(LoggerInterface::class)));

// 直接存入实例
$container->instance(Config::class, $config);

// 解析(构造函数依赖自动按类型注入)
$greeter = $container->make(Greeter::class);

use Kode\Core\Provider\ServiceProvider;

final class CacheServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // 注册阶段:登记绑定(其它服务可能尚未就绪)
        $this->container->singleton(\Psr\SimpleCache\CacheInterface::class, RedisCache::class);
    }

    public function boot(): void
    {
        // 启动阶段:依赖已就绪,可做初始化(连接、订阅等)
    }
}

$app = App::boot([
    'runtime' => ['fiber'],          // 启动时启用协程
]);

$app->enableRuntime('process');      // 运行时再启用多进程(链式)

$app = App::boot([
    'runtime' => ['fiber', 'parallel'],   // 协程 + 并行(要求已 composer s() as $mode => $info) {
    printf("%s: %s (需 %s)\n",
        $mode,
        $info['installed'] ? '可用' : '未安装',
        implode(' ', $info['packages']),
    );
}

// 未安装时启用会抛清晰异常:
// RuntimeException: 启用运行时模式 parallel 需要先安装桥接包:composer 

$results = $app->runtime->runTasks([
    fn() => 'task-1@' . $app->runtime->getName(),
    fn() => 'task-2@coroutine',
]);
// 进程内运行时(cli/fiber/swoole/swow)可拿到各任务返回值;
// 多进程(process)子进程内存独立,返回值不回传父进程(适合副作用型任务)。