PHP code example of migears / web

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

    

migears / web example snippets



// resources/Users/___user_id___/Index.php

namespace App\Resources\Users\UserId;

use MiGears\Web\AbstractResource;
use MiGears\Web\Request;
use MiGears\Web\Response;

class Index extends AbstractResource
{
    public function GET(Request $request): Response
    {
        $userId = (int) $this->param('user_id');
        return Response::json(['id' => $userId, 'name' => 'User ' . $userId]);
    }

    public function PUT(Request $request): Response
    {
        $userId = (int) $this->param('user_id');
        $body = $request->body;
        return Response::json(['id' => $userId, 'updated' => $body], 200);
    }

    protected function before(Request $request): ?Response
    {
        // Returning a Response short-circuits dispatch
        if ($request->header('X-Auth') === '') {
            return Response::json(['error' => 'unauthorized'], 401);
        }
        return null;
    }

    protected function after(Request $request, Response $response): Response
    {
        // Modify the response and return it
        return $response->withHeader('X-Powered-By', 'migears');
    }
}


use MiGears\Web\MiRest;
use MiGears\Web\Request;

$rest = new MiRest(
    baseDir: __DIR__ . '/resources',
    namespace: 'App\\Resources',
);

// Register only what needs configuration
$rest->set(PDO::class, fn() => new PDO('mysql:host=localhost;dbname=app', 'user', 'pass'));

$response = $rest->handle(Request::fromGlobals());
$response->send();

$rest->set(string $id, callable $factory): self   // Register a factory (lazy)
$rest->has(string $id): bool                       // Registered (factory pending or resolved)?
$rest->get(string $id): mixed                      // Resolve the instance (cached for reuse)

$rest->set(PDO::class, fn() => new PDO('mysql:host=localhost;dbname=app', 'user', 'pass'));

$rest->has(PDO::class);   // true — factory registered (not yet resolved)
$rest->get(PDO::class);   // 1st call runs the factory, caches the result
$rest->get(PDO::class);   // 2nd call returns the SAME cached instance

$rest->get('missing');    // throws NotFoundException — an unregistered id is an assembly mistake

class Users extends AbstractResource
{
    public function GET(Request $request): Response
    {
        $pdo    = $this->resolve(PDO::class);              // shared PDO from the container
        $logger = $this->resolve(LoggerInterface::class);  // and the shared logger
        $dao    = new UserDao($pdo, $logger);              // plain `new` — no container needed

        return Response::json($dao->getAll());
    }
}

$rest = new MiRest(baseDir: __DIR__ . '/resources', namespace: 'App\\Resources');

$rest->set(PDO::class,                    fn() => new PDO('mysql:host=localhost;dbname=app', 'user', 'pass'));
$rest->set(\Psr\Log\LoggerInterface::class, fn() => new Monolog\Logger('app'));
$rest->set(RedisCache::class,            fn() => new RedisCache(new Redis()));

public function handle(Request $request): Response

$rest->before(callable $handler): self      // Global before hook
$rest->after(callable $handler): self       // Global after hook
$rest->notFound(callable $handler): self    // Custom 404 handler
$rest->error(callable $handler): self       // Custom exception handler
$rest->set(string $id, callable $factory): self    // Register an entry (lazy)
$rest->has(string $id): bool                       // Is it registered?
$rest->get(string $id): mixed                      // Resolve the instance (cached)

$request->method      // HTTP method: GET, POST, PUT, DELETE...
$request->path        // Request path: /users/123
$request->query       // Query parameter array
$request->body        // Parsed body array (JSON/form)
$request->headers     // Request header array
$request->server      // $_SERVER array
$request->files       // Uploaded files array ($_FILES)

$request->header(string $name, mixed $default = null): mixed
Request::fromGlobals(): self

Response::json(mixed $data, int $status = 200): self
Response::html(string $html, int $status = 200): self
Response::redirect(string $url, int $status = 302): self
Response::empty(int $status = 204): self

$response->withHeader(string $name, string $value): self
$response->withStatus(int $status): self
$response->send(): void


// resources/Users/___user_id___/Index.php

namespace App\Resources\Users\UserId;

use MiGears\Web\AbstractResource;
use MiGears\Web\Request;
use MiGears\Web\Response;

class Index extends AbstractResource
{
    public function GET(Request $request): Response
    {
        $userId = (int) $this->param('user_id');
        return Response::json(['id' => $userId, 'name' => 'User ' . $userId]);
    }

    public function PUT(Request $request): Response
    {
        $userId = (int) $this->param('user_id');
        $body = $request->body;
        return Response::json(['id' => $userId, 'updated' => $body], 200);
    }

    protected function before(Request $request): ?Response
    {
        // 返回 Response 则短路分发
        if ($request->header('X-Auth') === '') {
            return Response::json(['error' => 'unauthorized'], 401);
        }
        return null;
    }

    protected function after(Request $request, Response $response): Response
    {
        // 修改响应后返回
        return $response->withHeader('X-Powered-By', 'migears');
    }
}


use MiGears\Web\MiRest;
use MiGears\Web\Request;

$rest = new MiRest(
    baseDir: __DIR__ . '/resources',
    namespace: 'App\\Resources',
);

// 只注册需要配置的服务
$rest->set(PDO::class, fn() => new PDO('mysql:host=localhost;dbname=app', 'user', 'pass'));

$response = $rest->handle(Request::fromGlobals());
$response->send();

$rest->set(string $id, callable $factory): self   // 注册工厂(懒加载)
$rest->has(string $id): bool                       // 是否已注册(工厂待执行或已解析)
$rest->get(string $id): mixed                      // 解析实例(缓存复用)

$rest->set(PDO::class, fn() => new PDO('mysql:host=localhost;dbname=app', 'user', 'pass'));

$rest->has(PDO::class);   // true — 工厂已注册(尚未解析)
$rest->get(PDO::class);   // 第 1 次调用:执行工厂并缓存结果
$rest->get(PDO::class);   // 第 2 次调用:返回同一个缓存实例

$rest->get('missing');    // 抛 NotFoundException —— 未注册的 id 属于装配错误

class Users extends AbstractResource
{
    public function GET(Request $request): Response
    {
        $pdo    = $this->resolve(PDO::class);              // 容器中的共享 PDO
        $logger = $this->resolve(LoggerInterface::class);  // 以及共享 logger
        $dao    = new UserDao($pdo, $logger);              // 普通 `new` —— 不需要容器

        return Response::json($dao->getAll());
    }
}

$rest = new MiRest(baseDir: __DIR__ . '/resources', namespace: 'App\\Resources');

$rest->set(PDO::class,                    fn() => new PDO('mysql:host=localhost;dbname=app', 'user', 'pass'));
$rest->set(\Psr\Log\LoggerInterface::class, fn() => new Monolog\Logger('app'));
$rest->set(RedisCache::class,            fn() => new RedisCache(new Redis()));

public function handle(Request $request): Response

$rest->before(callable $handler): self      // 全局前置钩子
$rest->after(callable $handler): self       // 全局后置钩子
$rest->notFound(callable $handler): self    // 自定义 404
$rest->error(callable $handler): self       // 自定义异常处理
$rest->set(string $id, callable $factory): self    // 注册条目(懒加载)
$rest->has(string $id): bool                       // 是否已注册
$rest->get(string $id): mixed                      // 解析实例(缓存)

$request->method      // HTTP 方法: GET, POST, PUT, DELETE...
$request->path        // 请求路径: /users/123
$request->query       // 查询参数数组
$request->body        // 解析后的 body 数组(JSON/表单)
$request->headers     // 请求头数组
$request->server      // $_SERVER 数组
$request->files       // 上传文件数组($_FILES)

$request->header(string $name, mixed $default = null): mixed
Request::fromGlobals(): self

Response::json(mixed $data, int $status = 200): self
Response::html(string $html, int $status = 200): self
Response::redirect(string $url, int $status = 302): self
Response::empty(int $status = 204): self

$response->withHeader(string $name, string $value): self
$response->withStatus(int $status): self
$response->send(): void

resources/
  Index.php              # GET /
  Users/
    Index.php            # GET /users, POST /users
    ___user_id___/
      Index.php          # GET /users/{user_id}, PUT /users/{user_id}, DELETE /users/{user_id}
      Posts/
        Index.php        # GET /users/{user_id}/posts
  Catchall/
    CatchAllResource.php # Fallback match for /catchall/*

resources/
  Index.php              # GET /
  Users/
    Index.php            # GET /users, POST /users
    ___user_id___/
      Index.php          # GET /users/{user_id}, PUT /users/{user_id}, DELETE /users/{user_id}
      Posts/
        Index.php        # GET /users/{user_id}/posts
  Catchall/
    CatchAllResource.php # 兜底匹配 /catchall/*