PHP code example of larkframe / template

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

    

larkframe / template example snippets


use LarkFrame\Route;

// 基础路由
Route::get('/users', [UserController::class, 'index']);
Route::post('/users', [UserController::class, 'store']);
Route::put('/users/{id}', [UserController::class, 'update']);
Route::delete('/users/{id}', [UserController::class, 'destroy']);

// 带参数的路由
Route::get('/users/{id:\d+}', function ($request) {
    $id = $request->route()->param('id');
    return json(['user_id' => $id]);
});

// 命令行路由
Route::shell('/migrate', [MigrateController::class, 'run']);

namespace App\Controller;

use LarkFrame\Request;

class UserController
{
    public function indexAction(Request $request)
    {
        $page = $request->input('page', 1);
        $users = \LarkFrame\Db::table('users')->paginate(15, ['*'], 'page', $page);
        return json(['code' => 0, 'data' => $users]);
    }

    public function showAction(Request $request)
    {
        $id = $request->route()->param('id');
        $user = \LarkFrame\Db::table('users')->where('id', $id)->first();
        return json(['code' => 0, 'data' => $user]);
    }
}

use LarkFrame\Db;

// 查询构建器
$users = Db::table('users')->where('status', 'active')->get();

// 多库切换
$orders = Db::use('order_db')->table('orders')->get();

// Eloquent Model
$user = \App\Model\UserModel::find(1);
$user = \App\Model\UserModel::create(['name' => 'John', 'email' => '[email protected]']);

use LarkFrame\Cache\Cache;

Cache::set('key', 'value', 3600);
$value = Cache::get('key');
Cache::delete('key');

use LarkFrame\Cache\Redis;

Redis::set('key', 'value');
Redis::get('key');
Redis::use('cache', 1)->set('key', 'value');  // 切换连接和数据库

use LarkFrame\Queue;

// 推送任务
Queue::push('emails', \App\Job\SendEmailJob::class, ['to' => '[email protected]']);

// 延迟推送
Queue::later('emails', 60, \App\Job\SendEmailJob::class, ['to' => '[email protected]']);

// 队列大小
$size = Queue::size('emails');

namespace App\Job;

use LarkFrame\Queue\Job;

class SendEmailJob
{
    public function handle(Job $job, mixed $data): void
    {
        // 处理逻辑
        $job->ack();
    }
}

use LarkFrame\MiddlewareInterface;
use LarkFrame\Request;
use LarkFrame\Response;

class AuthMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        if (!$request->header('authorization')) {
            // json() 状态码固定 200,自定义状态码用 ->withStatus()
            return json(['error' => 'Unauthorized'])->withStatus(401);
        }
        return $handler($request);
    }
}

// 全局中间件 — config/config.php 的 server.middleware
'middleware' => [
    \App\Middleware\CorsMiddleware::class,
],

// 路由中间件
Route::get('/admin', [AdminController::class, 'index'])
    ->middleware(AuthMiddleware::class);

use LarkFrame\Util;

Util::str()->mask('13800138000');           // 138****8000
Util::rand()->uuid();                       // UUID v4
Util::base64()->urlEncode($data);           // URL 安全 Base64
Util::str()->formatBytes(1048576);          // 1 MB
Util::file()->ensureDir($dir);              // 确保目录存在

// 原生 PHP 模板(模板文件 template/default/index.php)
return raw_view('default/index', ['username' => 'world'], 'php');

// Twig 模板(模板文件 template/user/test.html,示例路由 /user/test)
return twig_view('user/test', ['name' => 'larkframe'], 'html');

// config/notify.php
return [
    'mail' => ['host' => 'smtp.example.com', ...],
];

// app/Library/Notify.php
class Notify extends \LarkFrame\Library
{
    public function send()
    {
        $config = $this->config['mail'];  // 自动加载
    }
}

'server' => [
    'socketName' => 'http://0.0.0.0:8080',  // 监听地址
    'daemonize' => false,                    // 是否守护进程
    'worker' => [
        'count' => 4,                        // Worker 进程数
        'reusePort' => true,                 // 端口复用
    ],
    'middleware' => [...],                    // 全局中间件
],

return [
    'cron' => [
        'handler'    => \App\Task\CronTask::class,  // 任务处理类(必须)
        'options'    => ['interval' => 60],          // 传递给 run() 的选项
        'daemonize'  => false,                       // 是否守护进程
        'worker'     => ['count' => 1],              // Worker 进程数
        'pidFile'    => 'task-cron.pid',             // PID 文件(runtime/ 下)
        'stdoutFile' => 'task-cron.stdout.log',      // 标准输出文件(runtime/ 下)
        'logFile'    => 'task-cron.log',             // 日志文件(runtime/ 下)
    ],
];

namespace App\Task;

use LarkFrame\Worker;

class CronTask
{
    public static function run(array $options, array $args): void
    {
        $interval = $options['interval'] ?? 60;

        Worker::log("[CronTask] Starting, interval: {$interval}s");

        // 注册定时器
        Worker::$globalEvent->repeat($interval, function () {
            // 定时执行的逻辑
            Worker::log("[CronTask] tick");
        });
    }
}
bash
# 1. 创建项目
composer create-project larkframe/template myapp
cd myapp

# 2. 启动开发服务器
php server.php

config/
  config.php           # 主配置
  config.dev.php       # 开发环境覆盖
  config.prod.php      # 生产环境覆盖
bash
# 启动 Server(前台运行,开发调试)
php server.php

# 后台守护运行
# 在 config/config.php 中设置 'daemonize' => true,然后启动
php server.php

# 停止服务(通过 PID)
kill $(cat runtime/server.pid)
bash
# 执行 shell 路由
php shell.php migrate
php shell.php queue/work

# 路由参数
php shell.php users/import "file=data.csv"
bash
# 前台运行(默认 start)
php task.php cron

# 停止任务
php task.php cron stop

# 重启任务
php task.php cron restart

# 查看状态
php task.php cron status

# 带参数启动
php task.php cleanup "days=30"
bash
# Nginx 配置 — root 指向 public 目录
server {
    root /var/www/myapp/public;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;