PHP code example of binsuper / moon
1. Go to this page and download the library: Download binsuper/moon library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
binsuper / moon example snippets
$config = array(
// 必须配置项
'database_type' => 'mysql',
'database_name' => 'mydatabase',
'server' => '127.0.0.1',
'username' => 'root',
'password' => '123456',
'charset' => 'utf8',
// 可选参数
'port' => 3306,
// 可选,定义表的前缀
'prefix' => '',
// 连接参数扩展, 更多参考 http://www.php.net/manual/en/pdo.setattribute.php
'option' => [
PDO::ATTR_CASE => PDO::CASE_NATURAL,
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
],
'rec_times' => 2 // 断线后的重连次数
);
$config = array(
'database_type' => 'mysql',
//如果库名一致,则填写一个即可
'database_name' => ['mydatabase1', 'mydatabase2', 'mydatabase3'],
//第一个为主库,其它均为从库
'server' => ['192.168.0.100', '192.168.0.101', '192.168.0.102'],
//如果账号一致,则填写一个即可
'username' => ['root100', 'root101', 'root102'],
//如果密码一致,则填写一个即可
'password' => ['passwd100', 'passwd101','passwd102'],
'charset' => 'utf8',
//主从开关
'rd_seprate' => true,
'port' => 3306,
'prefix' => '',
'option' => [
PDO::ATTR_CASE => PDO::CASE_NATURAL,
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
],
);
//初始化配置,执行一次即可
\Moon\Moon::initCfg($config);
//单例对象
$moon = \Moon\Moon::instance();
$moon = \Moon\Moon::instance();
//实例化模型
$model = $moon->model("表名", "别名"); //“别名”是选填字段
//定义模型类
class MyModel extends \Moon\Model{
public $table = 'test'; //映射的表名
}
//实例化模型
$model = new MyModel();
class User extends \Moon\Model{
public $table = 'user'; //映射的表名
}
//新增
$user = new User();
$user->name = '张三';
$user->gender = '男';
$user_id = $user1->save(); //新增一个用户,并返回该用户的主键ID
//查询 + 修改
$user2 = new User();
$user2->load($user_id); //查找主键ID=$user_id的记录
$user2->name = '李四'; //将名称修改为李四
$user2->gender = '女'; //将性别修改为女
$user2->save(); //当主键ID不为空时,执行更新操作
//删除
$user2->remove(); //执行删除操作
//不会真的执行删除操作
//打印sql:DELETE from table_name where `id` = 1
//delete()函数的返回值为false
$model->where('id', 1)->debug()->delete();
$model->limit(10);//sql: limit 10
$model->limit(10, 5);//sql: limit 10 OFFSET 5, limit 5,10
//开启事务的方式有两种
//1. $model->handler()->transaction(function() {});
//2. $moon->transaction(function() {});
$result = $model->handler()->transaction(function() use ($model) {
$last_id = $model->value('name', '张三')->insert();
if (rand(0, 1) === 0) { //随机数字,如果为0则回滚,否则提交
return false;
}
return $last_id;
});
var_dump($result);// 值为false或者$last_id的值