mattsmithdev/pdo-crud-for-free

使使用 PDO(与 MySQL)进行数据库 CRUD 操作变得非常简单

1.0 2016-07-05 22:40 UTC

This package is auto-updated.

Last update: 2024-09-22 01:56:38 UTC


README

Build Status Latest Stable Version Total Downloads Latest Unstable Version License

此软件包提供了一些类,旨在以简单的方式为使用 PDO(与 MySQL)的程序员提供一些实例 CRUD(创建-读取-更新-删除)方法,'免费',只需通过继承 \Mattsmithdev\PdoCrud\DatabaseTable

所有代码都遵循 PSR-1、PSR-2 编码标准。类遵循 PSR-4 自动加载标准。

安装

通过 Composer

$ composer require mattsmithdev/pdo-crud-for-free

注意 - 在我熟悉 SemVer(并达到 1.0.0 或更高版本)之前,您需要强制下载 dev-master,如下所示

$ composer require mattsmithdev/pdo-crud-for-free=dev-master

使用方法

此示例假设您有一个名为 'products' 的 MySQL 数据库表,其中包含 'id' 和 'description' 列。您需要编写相应的类 'Product'(注意首字母大写 ...)。

// file: /src/Product.php
namespace <MyNameSpace>;

class Product extends \Mattsmithdev\PdoCrud\DatabaseTable 
{
    // private properties with EXACTLY same names as DB table columns
    private $id;
    private $description;
    
    public function getDescription()
    {
        return $this->description;
    }
}
// file: /public-web/index.php or /src/SomeController->method()

require_once __DIR__ . '/<PATH_TO_AUTLOAD>';

// the DatabaseManager class needs the following 4 constants to be defined in order to create the DB connection
define('DB_HOST', '<host>');
define('DB_USER', '<db_username>');
define('DB_PASS', '<db_userpassword>');
define('DB_NAME', '<db_name>');

// get all products from DB as array of Product objects
$products = \<MyNameSpace>\Product::getAll();

// outputs something like:
//  hammer, nail, nuts, bolts
foreach ($products as $product){
    print $product->getDescription() . ', ';
}

有关更多详细信息,请参阅下面。还有在 GitGub 上的完整示例 Web 应用程序项目:(pdo-crud-for-free-example-project)[https://github.com/dr-matt-smith/pdo-crud-for-free-example-project]

更详细的使用说明(和重要假设)

假设 1:lowerCamelCase - 数据库表列名与 PHP 类属性匹配

此工具假设您的数据库表列名及其对应的 PHP 私有类属性名称以一致的方式命名为 'lowerCamelCase',例如。

id
title
category
price

假设 2:小写复数数据库表名称映射到大写单数 PHP 类名称

如果您有一个数据库表 'products',则将对应到 PHP 类 'Product'

表名称是小写的,且是复数名词,例如 'users'。PHP 类名称首字母大写,且是单数名词,例如 'User'

假设 3:PHP 类没有构造函数

由于 PDO 的性质,当将数据库行转换为对象实例时,会填充对象的属性,因此对应于您的数据库表的 PHP 类没有构造函数

因此,您将创建一个新的对象,并使用对象的公共 'setter' 方法,例如。

$p = new Product();
$p->setDescription('hammer');
$p->setPrice(9.99);
etc.

步骤 1:创建您的数据库表

例如,创建您的表(具有整数 'id' 字段,主键,自增)

例如,存储 DVD 数据的 SQL 表

id:int (primary key, autoincrement)
title:text
category:text
price:float

步骤 2:创建相应的 PHP 类,并从 Mattsmithdev\PdoCrud\DatabaseTable 继承

例如。

<?php
namespace Whatever;

use Mattsmithdev\PdoCrud\DatabaseTable;

    class Dvd extends DatabaseTable
    {
        private $id;
        private $title;
        private $category;
        private $price;
        
        // and public getters and setters ...

步骤 3:现在使用 '神奇出现' 的静态数据库 CRUD 方法

例如,要从表 'dvds' 获取所有 DVD 记录的数组,只需编写

$dvds = Dvd::getAll();

::getAll()

此方法返回对应数据库表每一行的对象数组

// array of Dvd objects, populated from database table 'dvds'
$dvds = Dvd::getAll();

::getOneById($id)

此方法返回具有给定 'id' 的对应数据库表记录的类的一个对象(如果不存在具有该主键 id 的记录,则返回 'null')

// one Dvd object (or 'null'), populated by row in database table 'dvds' with id=27
$dvds = Dvd::getOneById(27);

::delete($id)

此方法根据给定的 'id' 删除相应的记录,根据删除操作的成功与否返回 true/false

// delete row in database table 'dvds' with id=12
$deleteSuccess = Dvd::delete(12);

::insert($dvd)

此方法根据提供对象的内 容在数据库中添加一行新记录(如果对象中存在 'id',则忽略,因为表是自增的,所以由数据库分配新的、唯一的 'id'),返回新记录的 'id'(如果插入出错则返回 -1)

// delete row in database table 'dvds' with id=12
$dvd = new Dvd();
$dvd->setTitle('Jaws II');
$dvd->setCategory('thriller');
$dvd->setPrice(9.99);

// create the new Dvd row
$id = Dvd::insert($dvd);

// decision based on success/failure of insert
if ($id < 0){
    // error action
} else {
    // success action
}

::update($dvd)

此方法基于提供对象的内 容在数据库中添加或更新现有行,根据操作的成功与否返回 true/false

例如。

// update DB record for object 'dvd'
$updateSuccess = Dvd:update($dvd);

::searchByColumn($columnName, $searchText))

在给定的列上使用给定的搜索文本执行 SQL '%' 通配符搜索,返回与 SQL 'LIKE' 查询匹配的对象数组

例如。

// get all Dvds with 'jaws' in the title
$jawsDvds = Dvd::searchByColumn('title', 'jaws');

自定义 PDO 方法

如果 'free' DB 方法不足,可以很容易地向您的 PHP 类中添加自己的方法,这些方法与您的数据库表相对应。

以下是一个可以添加到 Product 类中的方法,允许通过 'id' 和 'description' 中的文本进行自定义搜索

/**
 * illustrate custom PDO DB method
 * in this case we search for products with an id >= $minId, and whose descrption contains $searchText
 *
 * @param $minId
 * @param $searchText
 *
 * @return array
 */
public static function customSearch($minId, $searchText)
{
    $db = new DatabaseManager();
    $connection = $db->getDbh();

    // wrap wildcard '%' around the serach text for the SQL query
    $searchText = '%' . $searchText . '%';

    $sql = 'SELECT * FROM products WHERE (description LIKE :searchText) AND (id > :minId)';

    $statement = $connection->prepare($sql);
    $statement->bindParam(':minId', $minId, \PDO::PARAM_INT);
    $statement->bindParam(':searchText', $searchText, \PDO::PARAM_STR);
    $statement->setFetchMode(\PDO::FETCH_CLASS, '\\' . __CLASS__);
    $statement->execute();

    $products = $statement->fetchAll();

    return $products;
}

以下是其在控制器函数中的使用示例

// get products from DB as array of Product objects - id > minId, description containing $searchText
$minId = 2;
$searchText = 'er';
$products = Product::customSearch($minId, $searchText);

// outputs something like:
//  [5] pliers
//  [7] hammer
foreach ($products as $product){
    print '<p>';
    print 'id [' . $product->getId() . '] ';
    print $product->getDescription();
}

//  [1] nut -- not listed due to search criteria

变更日志

请参阅 CHANGELOG 了解最近的变化。

测试

$ composer test

贡献

请参阅 CONTRIBUTINGCONDUCT 了解详细信息。

安全

如果您发现任何与安全相关的问题,请通过电子邮件 dr_matt_smith@me.com 而不是使用问题跟踪器。

鸣谢

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅 许可证文件