PHP code example of zoujingli / type-orm

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

    

zoujingli / type-orm example snippets




declare(strict_types=1);

use app\model\User;
use Type\Orm\Db;
use Type\Orm\ModelException;

/**
 * 应用服务显式声明输入白名单,模型保留当前租户及软删除约束。
 *
 * @return list<array<string, mixed>>
 */
function findAdultUsers(string $name): array
{
    $models = User::search(['name' => $name])->equal('name')->query()
        ->where('age', '>=', 18)
        ->orderBy('id')
        ->limit(20)
        ->get();
    return array_map(static fn (User $user): array => $user->project(['id', 'name', 'age']), $models);
}

/** 事务体不接收连接,失败不自动重试写入。 */
function renameUser(int $id, string $name): string
{
    return Db::transaction(static function () use ($id, $name): string {
        $user = User::query()->find($id);
        if ($user === null) {
            throw new ModelException('user_not_found', '用户不存在');
        }
        $user->set('name', $name);
        return $user->save();
    });
}



declare(strict_types=1);

namespace app\model;

use Type\Orm\Attribute\Table;
use Type\Orm\Model;

/** 用户数据;只向响应投影业务明确允许的字段。 */
#[Table('users')]
final class User extends Model
{
    public int $id;
    public string $name;
    public int $age;
}