elchroy/potatoorm

一个简单的PHP数据库对象关系映射包。

dev-develop 2016-04-01 16:37 UTC

This package is not auto-updated.

Last update: 2020-01-02 20:27:17 UTC


README

Coverage Status StyleCI Build Status Scrutinizer Code Quality

PotatoORM

一个简单的PHP数据库对象关系映射包。

##安装

要运行此包,您必须安装PHP 5.5+Composer

首先下载包。

$ composer require Elchroy/PotatoORM

安装Composer。

$ composer install

##设置配置

此包支持以下数据库引擎

  • MySQL
  • SQLite3

要开始使用此包,请确保您已经设置了一个数据库(上述之一)。

  • 数据库已设置。数据库应与PDO兼容。

从应用的根目录,打开(或创建)一个名为config.ini的文件。

对于MySQL

如果首选数据库是MySQL,请按如下方式编辑config.ini文件。

[database]
host = localhost
username = username_of_database
password = ****
dbname = name_of_database
adaptar = mysql

对于SQLite3

如果首选数据库是SQLite3,请按如下方式编辑config.ini文件。

[database]
adapter = sqlite
sqlite_file = name_of_database_file

对于SQLite3数据库,请确保将数据库文件存储在应用的根目录中,与config.ini文件在同一目录。

一旦设置了工作数据库,请确保数据库中有一个表。除非已创建,否则请创建一个表。

  • 注意,表名必须与期望的类名相同。同时,表名必须全部小写。

  • 表必须有一个名为id的列,其值为int类型,并且必须将其设置为表的主键。否则,可能会遇到一些错误。

以下简单的SQL查询将创建一个具有4列的book表。

CREATE TABLE 'book' (id int NOT NULL AUTOINCREMENT PRIMARY, title varchar(255), author varchar(255)), pages int.

此时,包已准备好与数据库和表通信。

用法

#####创建一个自定义类以扩展PotatoModel类。

class Book extends PotatoModel
{

}

类名必须与数据库中设置的表名相同。

#####创建该类的实例。

$book1 = new Book();

$book2 = new Book();

#####定义应该保存到数据库表中的一些类属性。

确保定义的属性与数据库表列的名称相同。

// Add a first book
$book1->title = "Parry Holter : Cage of Umpires";
$book1->author = "Elchroy Cresly";
$bolt1->pages = 350;

// Add a second book
$book2->title = "Under Mountains";
$book2->author = "Zendel Shezery";
$bolt2->pages = 350;

#####将新记录保存到表中。

// Save the two new books.
$book1->save();
$book2->save();

#####从数据库中查找记录。

// Find the book with ID of 2.
$book = Book::find(2);
echo $book->title;
==> "Under Mountains"
echo $book->author;
==> "Zendel Shezery"
echo $book->pages;

#####更新数据库中的记录。

$book = Book::find(2); // '2' is the ID of the book to be found.
$book->author = "Sia Merica" // Edit the author of the book.
$book->save(); // Save the book with the new author.

// Check if the book has been updated.
$b = Book::find(2); // The same book with the same ID.
echo $b->title;
==> "Under Mountains"
echo $b->author;
==> "Sia Merica"

#####从数据库中删除记录。

$book = Book::destroy(2); // '2' is the ID of the book to be deleted.

// The book has been deleted and an exception is thrown.
$b = Book::find(2); // 2 is the ID of the book that was deleted.

Record 2 : Not found found in this table (book).;
...

##测试

要测试此包,您可以使用PHPUnit,在命令行(WindowsOS)或终端(MacOS)中。

注意:确保先cd到应用的根目录。

$ phpunit