nicollassilva/simplephp

此包已被废弃,不再维护。未建议替代包。

一个小型 CRUD 项目,旨在协助日常流程并加快与数据库通信的过程。

v1.9.0 2020-09-08 22:50 UTC

README

注意:此包已被 MinasORM 包替代。

Maintainer Scrutinizer Code Quality PHP from Packagist Software License Latest Version Build Status Code Intelligence Status Total Downloads

Um pequeno projeto CRUD desenvolvido para auxiliar as rotinas diárias e acelerar o processo de comunicação com o banco de dados com segurança e transparência。

一个小型 CRUD 项目开发用于辅助日常流程并加快与数据库通信的过程,具有安全性和透明性。

入门

一些注意事项和分步指南,以便您下载并安装此包。

先决条件

要使用 SimplePHP,您需要具备以下条件:

PHP ^7.2.5
EXT-PDO *

安装

SimplePHP 可以通过 composer.json 或通过 命令行终端 安装

composer require nicollassilva/simplephp

composer.json

"nicollassilva/simplephp": "^1.9"
>>>>>>> Stashed changes

连接

要配置数据库连接,您必须访问: Source\Root\Config.php。以下是要查找的文件示例

protected $config = [
        "driver" => "mysql",
        "hostname" => "localhost",
        "charset" => "utf8mb4",
        "port" => 3306,
        "username" => "root",
        "password" => "",
        "database" => "",
        "timezone" => "America/Sao_Paulo",
        "pathLog" => __DIR__ . "/../../../../../your-log.log",
        "options" => [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_CASE => PDO::CASE_NATURAL,
            PDO::ATTR_ORACLE_NULLS => PDO::NULL_EMPTY_STRING
        ]
    ];

您的模型示例

完成数据库配置后,在项目根目录创建一个文件夹,用于存放您的 模型,并创建该类。

  • 您应该扩展并使用 SimplePHP 类命名空间,如下例所示
namespace Models;

use SimplePHP\Model\SimplePHP;

class User extends SimplePHP {

    function __construct()
    {
        /**
         * @param string Table Name
         * @param string Primary Key
         */
        parent::__construct('users', 'id');
    }
}
  • 您需要从 SimplePHP 类继承您的模型,并在魔术构造方法中,使用所引用模型的表名和主键调用父构造函数。

首次使用

完成所有上述步骤后,在项目根目录创建一个 index.php,在 composer 自动加载和在您的模型类中给出 require,之后,实例化您的模型,您就可以开始使用 SimplePHP 了。以下是一个示例

    require "vendor/autoload.php";
    require "models/user.php";

use Models\User;

    $userModel = new User();
    $user = $userModel->find()->execute();

安装错误

一些错误及其解决方法

致命错误:未捕获错误:类 'SimplePHP\Model\SimplePHP' 未找到

要修复此问题,请在项目根目录中执行以下命令

composer dump -o

文档

方法

find

use Models\User;

$userModel = new User();

/** find all users */
$user = $userModel->find()->execute();

/** find user by id */
$user = $userModel->find(5)->execute();

/** find users and return the total result count */
$count = $userModel->count()->execute();

/** find user with one where */
$user = $userModel->where([
                                     ['name', '=', 'Nicollas']
                                ])->execute();

/** find user with several where. Conditional AND default */
$user = $userModel->where([
                                     ['name', '=', 'John'],
                                     ['email', '=', 'johnmoppans@gmail.com']
                                ])->execute();

/** find user with LIKE. Conditional AND default */
$user = $userModel->where([
                                     ['name', 'LIKE', '%Guilherme%'],
                                     ['email', '=', 'guilherme@gmail.com']
                                ])->execute();

/** find user with conditional where. Condicional OR */
$user = $userModel->where([
                                     ['name', 'LIKE', '%Nicollas%'],
                                     ['name', 'LIKE', '%Nicolas%']
                                ], 'OR')->execute();

/** find users by name = Nicollas OR name = Nicolas */
$user = $userModel->where([
				     ['name', '=', 'Nicollas']
			])
			->orWhere([
				     ['name', '=', 'Nicolas']
			])->execute();

/** find user using the basic structure query */
$user = $userModel->whereRaw("name = 'Nicollas'")->execute();

/** find users with limit */
$user = $userModel->limit(5)->execute();

/** find users with limit & offset */
$user = $userModel->limit(5)->offset(5)->execute();

/** find users with skip & take | the same as limit & offset */
$user = $userModel->take(5)->skip(5)->execute();

/** find users with orderBy. second parameter optional, default ASC */
$user = $userModel->orderBy('id', 'DESC')->orderBy('name')->execute();

/** find users and return results as attributes. EXAMPLE: $user->name instead of $user['name'] */
$user = $userModel->find()->execute(true); 

/** find users with specific columns. */
$user = $userModel->find()->only(['name', 'id', 'email'])->execute();

/** find users creating exceptions in columns. */
$user = $userModel->find(5)->except(['password'])->execute();

/** search in other database table */
$user = (new User())->useTable('posts')->find()->where([['owner_id', '=', $user->id]])->execute();

/** debug query for possible errors | return string */
$user = $userModel->whereRaw("uuid = 'f031b537-672f-4fba-b8a6-af45e778ad93'")->debugQuery();

/** group by method */
$user = $userModel->groupBy('id');
  • 注意: except() 方法不能与 execute(true) 方法连用,只有没有参数 true 的 execute() 方法。

  • 注意: except() 方法仅在查找特定信息时有效,在多维数组中无效。这个问题将会很快修复。

  • 所有方法都互相友好,这意味着您可以进行复杂查询。真实示例

/** Search for a user's posts varying between the privacy in which it was saved */
/** You can pass false as a fourth argument, the class will understand that you are trying to relate tables and will not put single quotes */

$posts = (new User())->useTable('posts p, users u')
                             ->where([['u.id', '=', $user['id'] ?? $visit['id']],
                                      ['u.id', '=', 'p.user_id', false], /** example of the fourth argument for relating tables */
                                      ['p.privacity', '<=', isset($privacity) && is_array($privacity) ? 3 : ($visit['url'] != $flag ? 1 : 4)]])
                             ->only(['p.*', 'u.name', 'u.url', 'u.i_profile'])
                             ->limit(10)
                             ->orderBy('p.id')
                             ->execute();

destroy

use Models\User;

$userModel = new User();
$user = $userModel->find(3)->execute(true);

    /** @return null|bool */
    if($user->destroy()) {
        echo "Success delete!";
    }
  • 注意: 删除信息时,您需要注意该信息有一个引用,即主键。

save (update)

use Models\User;

$userModel = new User();
$user = $userModel->find(5)->execute(true);
$user->name = "Other name";
$user->email = "anyemail@gmail.com";

    /** @return null|bool */
    if($user->save()) {
        echo "Success!";
    }
  • 注意: 保存信息时,您需要注意该信息有一个引用,即主键。
  • 注意: 您可以使用 only() 方法仅获取必要的信息,但在编辑时,您可以传递数据库表中存在的任何列,系统将进行处理并插入。示例
use Models\User;

$userModel = new User();
$user = $userModel->find(8)->only(['id', 'name'])->execute(true);
$user->name = "Russian Gabolev";

$user->email = "anyemail@gmail.com";
/** This informations was not called from the database, but they exist. */
$user->updated_at = time();

    /** @return null|bool */
    if($user->save()) {
        echo "Success!";
    }
  • 注意: 失败时将返回 NULL,成功完成时将返回 true。

create (insert)

use Models\User;

    $userModel = new User();
    $user = $userModel->request([
        "name" => "Dr. Haylie Bahringer",
        "email" => 'hayliebahringer@gmail.com', 
        "password" => 123456 // Encrypt before sending to the database
    ])->create();

也可以通过传递直接数组来实现

use Models\User;

    $userModel = new User();
    $_POST = [
        "name" => "Hadjei Moccab",
        "email" => "hadjeiofficial@gmail.com",
        "password" => 123456 // Encrypt before sending to the database
    ];
    $user = $userModel->request($_POST)->create();
  • 注意: 失败时将返回 NULL,成功完成时将返回 true。

其他方法

use Models\User;

    $userModel = new User();
    $user = $userModel->find(18)->execute(true);
    
    /** @return string | @param string $hash, @param Array $options */
    $user->password = $userModel->hashFormat($_POST['password']);
    
    /** @return string | @param string $url */
    $user->home = $userModel->urlFormat('Dr. John,Sik!@'); // dr-john-sik
    
    /** @return bool | @param string $email */
    if(!$userModel->validateEmail($_POST['email'])) {
        echo "Invalid email!";
    }
    
    /** @return bool | @param string $pass */
    if(!$userModel->validatePassword($_POST['password'])) {
        echo "Invalid password!";
    }
    
    /** @return bool | @param string $phone */
    if(!$userModel->validatePhone($_POST['telephone'])) {
        echo "Invalid telephone!";
    }
    
    /** @return bool | @param int $size */
    $user->recovery_token = $userModel->aleatoryToken(15);
    
    $user->save()
  • 上述方法的指南
  • hashFormat:使用原生的 password_hash 函数加密密码。
  • urlFormat:将字符串格式化为友好的 URL。
"Pác^kà@gê Sí#mp%lePHP" -> "pac-ka-ge-si-mp-lephp"
  • validateEmail:验证输入的电子邮件是否有效。全部为 true
fulano@saopaulo.com.br
chico@gmail.com
joao@empresa.info.br
maria_silva@registro.br
rafa.sampaio@yahoo.com
fulano+de+tal@escola.ninja.br
  • validatePassword:检查密码是否包含大写和小写字母、特殊字符和数字,且长度大于 6 个字符,小于 20 个字符。
123456 // false
QUASE123! // false
#OpA1 // false
#essaSenhaEGrande1234 // false
#OpA1? // true
Foi123! // true
  • validatePhone:检查输入的手机号码是否有效。(不需要连字符)
(00)0000-0000
(00)00000-0000
0000-0000
00000-0000
  • aleatoryToken:生成给定大小的随机字符串。

执行过程中的错误

SimplePHP 生成错误时,它将出现在文件夹配置中配置的目录中,报告由 monolog 包 生成。

作者

许可证

本项目采用 MIT 许可证 - 详细信息请参阅 LICENSE.md 文件