PHP code example of toohamster / fleaphp-ex

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

    

toohamster / fleaphp-ex example snippets


// 基本路由
Router::get('/users', 'UserController@index');
Router::post('/users', 'UserController@store');

// 带参数路由
Router::get('/users/{id:\d+}', 'UserController@show');

// 路由分组
Router::group('/admin', function() {
    Router::get('/stats', 'AdminController@stats');
}, [new AuthMiddleware()]);

// 注册全局中间件
\FLEA::middleware(new CorsMiddleware());
\FLEA::middleware(new AuthMiddleware());

// 自定义中间件
class MyMiddleware implements \FLEA\Middleware\MiddlewareInterface
{
    public function handle(callable $next): void
    {
        // 前置处理
        $next();
        // 后置处理
    }
}

// 存储数据
flea_context()->set('user_id', 123);

// 读取数据
$user_id = flea_context()->get('user_id');

// 检查键是否存在
if (flea_context()->has('user_id')) {
    // ...
}

use FLEA\Auth\Jwt;

// 签发 Token
$token = Jwt::encode(['user_id' => 123], 7200);

// 验证 Token
$payload = Jwt::decode($token);

// 验证有效性
if (Jwt::verify($token)) {
    // Token 有效
}
bash
# 在项目根目录执行
php bin/flea-cli --project-dir=demo

# 访问 http://127.0.0.1:8081/index.php