wdes/simple-php-model-system

简单的PHP模型系统

v1.3.0 2022-05-10 14:09 UTC

This package is auto-updated.

Last update: 2024-09-04 16:24:39 UTC


README

Lint and analyse files Run phpunit tests codecov Version License PHP Version Require maintenance-status

简单的PHP模型系统

为什么?

本项目旨在为非composer环境下的模型使用提供简便途径。因此,本项目保持了极简的设计。用户可以复制src/目录下的所有类,并开始使用这个库。但这同样适用于composer环境。

如何使用

连接到现有的PDO连接

<?php
declare(strict_types = 1);

use SimplePhpModelSystem\Database;

require_once __DIR__ . DIRECTORY_SEPARATOR . 'autoload.php';// Use your autoloader or require classes by hand

$db         = new Database(null);
// With Symfony: EntityManagerInterface $em
$db->setConnection($em->getConnection()->getNativeConnection());// Wants a PDO connection object class

通过配置连接

<?php
declare(strict_types = 1);

use SimplePhpModelSystem\Database;

require_once __DIR__ . DIRECTORY_SEPARATOR . 'autoload.php';// Use your autoloader or require classes by hand

$configFile = __DIR__ . DIRECTORY_SEPARATOR . 'config.php';// Copy config.dist.php and fill the values
$config     =  require $configFile;
$db         = new Database($config);
$db->connect();// Will throw an exception if not successfull

管理模型

<?php

use examples\User;

// Without models

$statement = $db->query(
    'SELECT 1'
);
$this->data = [];
while (($row = $statement->fetch(PDO::FETCH_ASSOC)) !== false) {
    $this->data[] = $row;
}
var_dump($this->data);


// With a model

$user1 = User::create(
    '5c8169b1-d6ef-4415-8c39-e1664df8b954',
    'Raven',
    'Reyes',
    null
);
$user1->save();// If you forget this line, it will only exist in memory
$user1 = User::findByUuid('5c8169b1-d6ef-4415-8c39-e1664df8b954');// Find the user back
$user1->toArray();
//[
//    'user_uuid' => '5c8169b1-d6ef-4415-8c39-e1664df8b954',
//    'first_name' => 'Raven',
//    'last_name' => 'Reyes',
//    'date_of_birth' => null,
//]
$user1->refresh(); // Get it back from the DB
$user1->setLastName('last_name', 'Ali-2');// Change an attribute value (build your own setters using the example)
$user1->update();// Update it
$user1->delete();// Delete it
User::deleteAll();// Delete all
// And more functions, see AbstractModel class