gpt4 book ai didi

php - 如何实现分层cms站点?

转载 作者:搜寻专家 更新时间:2023-10-30 21:42:00 27 4
gpt4 key购买 nike

我正在编写一个学习 CMS 的小项目,但遇到了阻碍我完成下一步的障碍。我知道我应该考虑 KISS(保持简单,愚蠢),但我认为能够对页面进行分层分组会很好。

问题是我希望页面 [root]->fruits->tropical->bananas 只能从这个 url 访问:http://localhost/cms/fruits/热带/香蕉/。到目前为止,我想到的是 cms 表有一个指向其父项的父字段。问题是:如何以尽可能少的查询/高效地解析 uri 地址并从数据库中选择一行?

Table structure:
Id
Slug
...
...
...
ParentId

我们诚挚地接受所有帮助和建议。

最佳答案

这是我用来测试这个的表结构 -

CREATE TABLE  `test`.`pages` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`slug` varchar(45) NOT NULL,
`title` varchar(45) NOT NULL,
`content` text NOT NULL,
`parent_id` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UQ_page_parent_id_slug` (`parent_id`,`slug`),
CONSTRAINT `FK_page_parent_id` FOREIGN KEY (`parent_id`) REFERENCES `pages` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

注意 (parent_id, slug) 上的唯一键。这是从以下查询中获得最佳性能的关键。我用 50k 行对此进行了测试,对于五个 slug 路径,它仍然在不到 1ms 的时间内返回 - /cms/slug-1/slug-2/slug-3/slug-4/slug-5/

这是我用来构建合适查询的 PHP 代码 -

<?php

// I will assume the rest of the url has already been stripped away
$url = '/fruits/tropical/bananas/';

// lets just make sure we don't have any leading or trailing /
$url = trim($url, '/');

// now let's split the remaining string based on the /
$aUrl = explode('/', $url);

/**
* Now let's build the query to retrieve this
*/

// this array stores the values to be bound to the query at the end
$aParams = array();

$field_list = 'SELECT p1.* ';
$tables = 'FROM pages p1 ';
$where = "WHERE p1.parent_id IS NULL AND p1.slug = ? ";

// this array stores the values to be bound to the query at the end
$aParams[] = $aUrl[0];

// if we have more than one element in our array we need to add to the query
$count = count($aUrl);

for ($i = 1; $i < $count; $i++) {

// add another table to our query
$table_alias = 'p' . ($i + 1);
$prev_table_alias = 'p' . $i;
$tables .= "INNER JOIN pages $table_alias ON {$prev_table_alias}.id = {$table_alias}.parent_id ";

// add to where clause
$where .= "AND {$table_alias}.slug = ? ";
$aParams[] = $aUrl[$i];

// overwrite the content of $field_list each time so we
// only retrieve the data for the actual page requested
$field_list = "SELECT {$table_alias}.* ";

}

$sql = $field_list . $tables . $where;

$result = $this->db->query($sql, $aParams);

关于php - 如何实现分层cms站点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9609976/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com