PHP code example of lite-view / framework

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

    

lite-view / framework example snippets




const WORKING_DIR = __FILE__;
View\Kernel\Visitor;
use LiteView\Support\Dispatcher;

// 定义路由
Route::get('/', function (Visitor $visitor) {
    return json_encode(['message' => 'Hello, LiteView!']);
});

Route::get('/user/{id}', function (Visitor $visitor, $id) {
    return json_encode(['user_id' => $id]);
});

// 处理请求
[$target, $params] = Route::match();
if ($target) {
    echo Dispatcher::work($target, $params, new Visitor());
} else {
    http_response_code(404);
    echo json_encode(['error' => 'Not Found']);
}

// 静态路由
Route::get('/hello', 'Controller@hello');
Route::post('/submit', 'Controller@submit');

// 参数路由
Route::get('/user/{id}', 'Controller@show');

// 可选参数
Route::get('/list/{page?}', 'Controller@list');

// 正则约束
Route::get('/file/{path}', 'Controller@file', [], ['path' => '.+']);

// 任意 HTTP 方法
Route::any('/api/data', 'Controller@data');

// 路由分组(支持前缀和中间件继承)
Route::group('api', function () {
    Route::get('/users', 'UserController@index');
    Route::post('/users', 'UserController@store');
});

// RESTful 资源路由(自动生成 index/store/show/update/destroy)
Route::apiResource('/users', UserController::class);

// 快捷路由(自动注册控制器所有公共方法)
Route::quick('/ctrl', MyController::class);

class LogMiddleware
{
    public function handle(Visitor $v, $next)
    {
        $start = microtime(true);
        $response = $next($v);
        $ms = round((microtime(true) - $start) * 1000, 2);
        return $response . " <!-- {$ms}ms -->";
    }
}

Route::get('/demo', 'Controller@demo', [LogMiddleware::class]);

$visitor = new Visitor();

// 获取 GET / POST / JSON 输入(自动合并)
$name = $visitor->input('name', 'default');
$all = $visitor->input();          // ArrayObject

// 批量取值 / 排除字段
$data = $visitor->only(['name', 'email']);
$data = $visitor->except(['password']);

// 获取 GET / POST 原始数据
$get = $visitor->get('page', 1);
$post = $visitor->post('content');

// 获取客户端 IP
$ip = $visitor->ip();

// 登录 / 登出
$visitor->login(42);
$visitor->logout();

// Twig 模板(推荐)
View::setPath('/path/to/views');
return View::renderTwig('index.twig', ['title' => 'Home']);

// 原生 PHP 模板
View::renderFile('page.php', ['data' => $data]);

// 生成 Token(有效期 1 小时)
$token = ApiToken::create(['user_id' => 42], 3600, 'api');

// 验证 Token
$result = ApiToken::auth($token, 'api', $info);
// 返回值:0=成功, 1=空, 2=签名错误, 3=过期, 4=Guard不匹配

// 密码哈希
$hash = ApiToken::passwdMake('password');
$ok = ApiToken::passwdAuth('password', $hash);

// 使用默认通道
Log::info('user_login', ['user_id' => 42]);
Log::error('db_error', ['sql' => $sql]);

// 使用自定义通道
$logger = Log::employ('custom');
$logger->debug('debug_info');

root_path('storage/logs/app.log');  // 获取相对于项目根目录的绝对路径
cfg('app_url');                      // 读取配置
cfg('database.host', 'localhost'); // 读取嵌套配置,带默认值
domain();                            // 自动推断站点 URL
cors('/api');                        // 根据配置输出 CORS 响应头
bash
php -S 127.0.0.1:8000 public/index.php
json
{
    "cors": {
        "paths": ["*"],
        "allow_origins": "*",
        "allow_methods": "POST, GET, OPTIONS",
        "allow_headers": "*"
    }
}