hellsan631/logosdb

一个用于创建简单数据库交互的数据库微框架,无需完整框架

安装: 31

依赖项: 0

建议者: 0

安全: 0

星级: 1

关注者: 2

分支: 0

公开问题: 7

类型:项目

v1.5.1 2014-12-28 01:08 UTC

README

Build Status Code Climate

LogosDB是一个数据库微框架,用于创建简单的数据库交互,无需完整的MVC结构。

对于小型项目、创建API或当您不希望或不需要实现功能齐全的MVC框架(Phalcon、Laravel、CodeIgniter、Zend)时,LogosDB将为您提供支持。LogosDB是一个简洁的模型交互框架,用于处理数据库中的对象。

版本1.5.*

1.5.*在框架中引入了命名空间。命名空间反映了文件夹层次结构,并在使用多个框架时有所帮助。在1.5版本更新期间,名称和文件夹结构可能会有所变动。

入门

需求

Requires PHP 5.5+
Requires PDO

安装(通过composer)

通过composer安装很简单。只需将以下内容添加到您的composer.json文件中

{
    "require": {
        "hellsan631/logosdb": "1.5.*"
    }
}

运行composer update/install命令后,使用logos对象扩展类

class User extends Logos\DB\MySQL\Model{
    public $username;
    public $email;
}

并确保包含您的自动加载器

include "./vendor/autoload.php";

对于那些没有composer的人,只需下载zip文件,并在PHP头部包含自动加载文件

创建模型

为数据库中您想要使用的每个表创建一个对象类。

//example object
class User extends Logos\DB\MySQL\Model{

    //public $id; already defined in the Database_Object class.

    public $username;
    public $email;

}

数据库设置

我们使用config类,它创建了一个简单的单例,用于输入我们的数据库连接数据。请将其添加到您的头部某个位置(或者您可以将此添加到autoload.php中)

use Logos\DB\Config;

//Database settings
Config::write('db.host', 'localhost');
Config::write('db.name', 'db_name');
Config::write('db.user', 'db_user');
Config::write('db.password', 'db_pass');

数据库模式

MySQL

Each table in your database should have an ID field, which is a incremental primary
index. If you want a table to use a date, use the timestamp format, and include
date in the name of the field.

用法

要快速了解类及其功能,请访问数据库接口 https://github.com/hellsan631/LogosDB/blob/92a702f60fbf8b2e351bfd6f2d505e391d4a894c/lib/Logos/DB/HandlerInterface.php

在数据库中创建新对象

对象可以是变量声明,也可以是静态创建(这需要较少的内存和时间)

//Object as a variable
$user = new User(["username" => "testing", "email" => "email@email.com"]);
$user->createNew();

//Same thing, but done statically (returns the ID of the created object)
User::createSingle(["username" => "testing", "email" => "email@email.com"]);

将多个对象创建到数据库中

您可以通过多种方式创建对象。

//Want to create 100 new identical objects?
User::createMultiple(["username" => "testing", "email" => "email@email.com"], 100);

//want each object to be different?
$users = [];
$count = 0;

while($count < 100){
    array_push($users, ["username" => "testing",
                        "email" => "email@email.com",
                        "other_var" => $count]);

    $count++;
}

User::createMultiple($users);

保存数据库中已存在对象的更改

//Saving a single object
User::loadSingle(["id" => 10])->save(["email" => "newEmail@gmail.com"]);

//or

User::saveSingle(["email" => "newEmail@gmail.com"], ["id" => 10]);

//saving to multiple objects at the same time
User::saveMultiple(["email" => "newEmail@gmail.com"], ["username" => "testing"]);

扩展查询语法

想要添加限制、orderBy或groupBy到查询结果中吗?

User::query('limit', 10);
User::query(['orderBy', 'limit'], ['id DESC', 10]);
User::query(['orderBy', 'limit'], ['id ASC, username DESC', 10]);
User::query(['orderBy' => 'id ASC', 'limit' => 10]);

//Add getList to the end of your query to get a list of that classes objects
User::query('limit', 100)->getList();

//how to use min/max for limit
//Send them in as array!
User::query('limit', [0, 10])->getList();
User::query('limit', ['min' => 0, 'max' => 10])->getList();

//Or if you want to use an array to add more,
User::query(['limit' => [0, 10], 'orderBy' => 'id ASC'])->getList();
User::query(['limit' => ['min' => 0, 'max' => 10], 'orderBy' => 'id ASC'])->getList();

添加的限制、orderBy或groupBy仅适用于下一个执行的查询。如果您连续执行两个查询,即

User::query('limit', 10);
User::loadMultiple($array1);

//limit 10 no longer applies here
User::CreateMultiple($array2);

如果您想让它影响那个调用,您需要在每个数据库调用中添加该查询。

此外,每次设置查询时,之前类型的查询都会被覆盖。

User::query('limit', 10);
User::query('orderBy', 'id ASC');
User::query('orderBy', 'id DESC');

//would load 10 users in id DESC order
User::loadMultiple($array1);

自动转换JSON

您可以在任何地方使用JSON或对象。

$JSON_STRING = '{"username": "testing", "email": "testing@mail.com"}';

$user = new User($JSON_STRING);//It works!

//Use JSON anywhere!
User::newInstance(["id" => 10])->save($JSON_STRING);
User::createMultiple($JSON_STRING, 100);

遵循模型

您不必担心发送到对象中的内容,或者在该对象中是否创建了动态声明的变量

$JSON_STRING = '{"username": "testing", "email": "testing@mail.com", "size": "small"}';

$user = new User($JSON_STRING);//It works!

var_dump($user);
//object(User)[98]
//    public 'username' => string 'testing' (length=7)
//    public 'email' => string 'testing@mail.com' (length=16)

$user->updateObject($JSON_STRING);

var_dump($user);
//object(User)[98]
//    public 'username' => string 'testing' (length=7)
//    public 'email' => string 'testing@mail.com' (length=16)
//    public 'size' => string 'small' (length=5)

//Now that the $user has a dynamic variable, lets try and save it.

$user->save();
//UPDATE user SET username = :username, email = :email WHERE id = :id

安全

有3个额外的安全类可以帮助PHP开发。目标是增强PHP 5.5的功能,使其符合行业标准,并使其易于使用。

密码类

密码类允许您加密/解密文本并生成安全的随机数。它使用MCrypt,这是一个内置的PHP扩展。目前,密钥是单向的,但很快就会改变。

使用密码类很简单。要加密某些内容

//Send a secure key to the cipher class.
$cipher = new Cipher("s3cur3k3y");

echo $cipher->encrypt("Hello World!");

//outputs "kRTIR6qDGYNumkoAMfwWMGNVPIUoODr0kvFMCmPDynM="

如果您想解密

echo $cipher->decrypt("kRTIR6qDGYNumkoAMfwWMGNVPIUoODr0kvFMCmPDynM=");

//outputs "Hello World!"

您还可以从Cipher获取一个随机密钥。强烈建议您使用cipher代替任何其他随机密钥/数字生成器以提高安全性,因为Cipher使用"openssl_random_pseudo_bytes()",这是PHP获取随机数据字符串最安全的方式。

//You can send in a length of key into the getRandomKey method, or just leave it blank for a default length of 22.
$randomKey = Cipher::getRandomKey();

密码类

密码类使用PHP 5.5内置的BCrypt实现来帮助保护用户密码。这无疑是存储密码最安全的方式,所有密码都应该以这种方式存储。

关于实现方法,我建议您查看我的其他项目,以及它是如何处理用户创建的。

创建新用户并正确保存其密码

newUser.php

$newUser = new User($_POST);

if($newUser->createNew())
    $_SESSION['result'] = "Successfully added new User";
else
    $_SESSION['result'] = "Unable to add new User";

header("Location: ./index.php");

使用用户登录

auth.php

$user = User::loadSingle(["username" => $_POST['username']]);

if(!$user && strlen($_POST['username']) > 6)
    $user = User::loadSingle(["email" => $_POST['username']]);

if(!$user){
    $_SESSION['result'] = "Couldn't find a user with that username/email";
}else{
    if($user->doAuth($_POST['password'])){

        $_SESSION['result'] = "Login Successful";
        $_SESSION['user'] = $user->toArray();

    }else{

        $_SESSION['result'] = "Incorrect Password";

    }
}

header("Location: ../login.php");

然后是处理所有这些的用户类

class.user.php

class User extends Logos\DB\MySQL\Model{

    public $username;
    public $email;
    public $password;
    public $salt;
    public $admin;
    public $auth_key;
    public $company_id;

    public function createNew(){

        $password = new Password($this->password);

        $this->password = $password->getKey();
        $this->salt = $password->getSalt();

        return parent::createNew();

    }

    public function verifyLogin($password){
        $passwordCheck = new Password($this->password, array('salt' => $this->salt, 'hashed' => true));

        return $passwordCheck->checkPassword($password);
    }

    public function verifyAuth(){
        if(!isset($_SESSION['auth_key']))
            return false;

        if($this->auth_key !== $_SESSION['auth_key'])
            return false;

        return true;
    }

    public function verifyAdmin(){
        if($this->admin === 0)
            return false;

        return true;
    }

    public static function deAuth(){
        foreach($_SESSION as $key => $value){
            if($key !== "result" || $key !== "Result" || $key !== "RESULT")
                unset($_SESSION[$key]);
        }

        return true;
    }

    public function doAuth($password, $level = 0){
        if($this->verifyLogin($password) === false)
            return false;

        if((int) $level === 1){
            if($this->verifyAdmin())
                return true;
        }else{
            if($this->verifyAuth())
                return true;
        }

        if($this->admin === 0 && $level === 1)
            return false;

        $_SESSION['auth_key'] = $this->auth_key = Cipher::getRandomKey();

        if($level === 1)
            $_SESSION['admin_key'] = $this->auth_key;

        return ($this->save() !== false) ? true : false;
    }
}

铁类

铁类有助于防止跨站请求伪造攻击。这样做可能有点复杂,但有了这个类,实现起来相当简单。

对于POST请求(例如登录表单)

login.php

<?php

    $iron = Iron::getInstance();

?>

<form id="login" action="auth.php" method="post">
    <input type="text" name="username" placeholder="Username" />
    <input type="password" name="password" placeholder="Password" />
    <?php
       echo $iron->generate_post_token(); //echos a post input with a new random key
    ?>
</form>

auth.php

$iron = Iron::getInstance();

if($iron->check_token() !== false){

    //its safe, you can do user authentication in here

}else{

    //warning, auth isn't safe. You should log the IP and lock down the system.

}

如果您还想保护您的GET请求

Info.php

    $iron = Iron::getInstance();

    $requestURL = "www.example.com/user.php?id=100123".$iron->generate_get_token();

    getUserData($requestURL);

user.php

$iron = Iron::getInstance();

if($iron->check_token() !== false){

    //its safe, you can do user authentication in here

}else{

    //warning, auth isn't safe. You should log the IP and lock down the system.

}

贡献

请随意分支、推送、拉取以及其他所有好的Git操作!

谢谢

(稍后扩展此README文件)

访问我的博客:http://mathew-kleppin.com/blog-page/