PHP code example of eternalphp / framework

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

    

eternalphp / framework example snippets


namespace app\Entity;

use framework\Database\Eloquent\Model;

class User extends Model
{
    // 指定关联的数据表(如果表名为 users,框架会自动推断,但显式指定更安全)
    protected $table = 'users';
    
    // 指定主键(默认为 id)
    protected $primaryKey = 'id';
}

use app\Entity\User;

// 根据主键查找当条数据
$user = User::first(1);

// 获取表内所有记录
$users = User::select();

// 条件查询与获取第一条结果
$adminUser = User::where('role', 'admin')->where('status', 1)->find();

// 链式查询与排序
$latestUsers = User::where('status', 1)
                    ->orderBy('created_at', 'DESC')
                    ->limit(10)
                    ->select();
                    
// 获取总条数
$count = User::where('status', 1)->rows();

// 简单分页功能 (自动返回带分页的数据集)
$pageData = User::where('status', 1)->paginate(15);

// 新增单条数据
$insertData = [
    'username' => 'testuser',
    'email'    => '[email protected]',
    'status'   => 1
];
// 返回新增后的主键 ID
$userId = User::insert($insertData);

// 条件更新
User::where('id', 1)->update([
    'status' => 0,
    'updated_at' => time()
]);

// 条件删除
User::where('id', 1)->delete();

$userModel = new User();

// 开启事务
$userModel->startTrans();

try {
    // 执行操作 1
    User::insert(['username' => 'user1']);
    // 执行操作 2
    User::where('id', 1)->update(['money' => ['+', 100]]);
    
    // 提交事务
    $userModel->commit();
} catch (\Exception $e) {
    // 出现异常则回滚
    $userModel->rollback();
}

class User extends Model
{
    // 一对多关联
    public function articles()
    {
        return $this->hasMany(Article::class, 'user_id', 'id');
    }
}

// 关联获取使用示例
$user = User::first(1);
// 获取其关联的文章对象或数组(根据实现细节可能会返回数据集)
$articles = $user['articles'];
// 或者作为方法添加附加条件
$articles = $user->articles()->where('status', 1)->select();