我观看了Yii2和Laravel,但我不想在我的应用程序中使用ActiveRecord,ORM和QueryBuilder,但如果我不使用50%的功能框架就可以删除它们。我想使用(cte,over,transations,存储过程和大查询)我也想使用单元测试。
你能告诉我如何在php上组织这个应用程序的结构,可能是使用模式Table Gateway和Table Module for split layer SQL code and php?
答案 0 :(得分:3)
坦率地说,我总是觉得使用PDO和SQL更简单。我经常发现自己正在与框架作斗争,特别是使用cte和存储过程。 Postgresql对json有很大的支持,因此它可以很容易地使用单个语句获取对象甚至复杂的嵌套对象。例如......
$sql = "select row_to_json(g) from (
select
firstname,
lastname,
(select json_agg(e) from (
select address from email where fk_user=user.id
)e
) as emails
from user
where id=:id
)g;"
$stmt = $db->prepare($sql);
$stmt->bindValue('id', 1, PDO::PARAM_INT);
$stmt->execute();
$obj = json_decode($stmt->fetchColumn(0));
答案 1 :(得分:1)
我已经为此启动了Pomm项目:利用PHP的Postgres功能。这是计算Fibonacci序列的完整示例:
<?php
//composer
$loader = require __DIR__ . '/vendor/autoload.php';
$pomm = new PommProject\Foundation\Pomm(
['my_db' => ['dsn' => 'pgsql://user:password@host/db_name']]
);
$sql = <<<SQL
WITH RECURSIVE
fibonacci AS (
SELECT 0::int4 as n, 1::int4 as m, 1::int4 as level
UNION ALL
SELECT
parent.m as n,
parent.n + parent.m as m,
parent.level + 1 as level
FROM fibonacci AS parent
WHERE level < $*::int4
)
SELECT n, m, level FROM fibonacci
SQL;
$iterator = $pomm['my_db']
->getQueryManager()
->query($sql, [20]) // pass 20 as max level to recurse
;
if (!$iterator->isEmpty()) {
foreach ($iterator as $row) {
printf("Level = %d (%d, %d).\n", $row['level'], $row['n'], $row['m']);
}
} else {
printf("The query returned no results.\n");
}
返回的结果转换为PHP等效类型(即,postgres中的布尔值是PHP中的布尔值,Datetime,DateInterval等相同)并且它支持几乎所有PostgreSQL类型(tstzrange,json,circle,point,HStore,inet)等等…)。
对于更复杂的项目,Pomm还提出了一个可选的对象模型管理器,它带有预定义的查询(CRUD)。可以(并建议)在每个实体类的专用方法中添加更复杂的查询(SQL连接)。
$model = $pomm['my_db']->getModel(CustomerModel::class);
$customer = $model
->findByPk(['customer_id' => $http_query['customer_id']])
;
$customer['email'] = $http_query['email']; // trigger setEmail() method
$model->updateOne($customer, ['email']); // update the email field only
它是一个面向投影的模型管理器,这意味着它使每个实体的SELECT部分中的字段可配置。可以使用所有Postgres函数丰富SELECT与计算字段,或删除所有与实体相关的SQL查询的字段。
有一个与Symfony2,Silex和Zend Framework集成的软件包。