我在WordPress中有一个依赖于外部数据库的自定义页面模板,它正在使用wpdb类来实现此目的.
这是我的代码:
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
</header><!-- .entry-header -->
<?php
class StudentsDatabase
{
private $db;
public function __construct() {
try {
$this->db = new wpdb(DB_USER, DB_PASSWORD, 'students_db', DB_HOST);
$this->db->show_errors();
} catch (Exception $e) {
echo $e->getMessage();
}
}
public function getStudentById($student_id)
{
return $this->db->get_results("SELECT * FROM `students` WHERE id=$student_id");
}
public function getSchoolByAreaCode($area_code)
{
return $this->db->get_results("SELECT * FROM `schools` WHERE area_code=$area_code;--");
}
}
$Students_DB = new StudentsDatabase();
$student_one = $Students_DB->getStudentById(1);
$school_one = $Students_DB->getSchoolByAreaCode(1);
?>
<div class="entry-content">
<?php
//do something with $student_one and $school_one ...
the_content();
?>
</div><!-- .entry-content -->
Run Code Online (Sandbox Code Playgroud)
好吧,我想知道这是否是正确的方法.安全方面或任何"其他"方式实际上.
从页面模板本身进行外部数据库调用感觉有点粗略.我应该在一些外部文件上注册这些功能,然后只在模板中使用它们吗?
eRI*_*RIZ 10
我认为最"干净"的方法是实现一个插件,它将成为您主题的API.当然,这取决于它是否仅仅是出于你自己的目的,因为Wordpress(到目前为止)缺少一个依赖管理器.
总结一下 - 在主题中使用然后这个API.
小智 6
将class声明等放在主题的functions.php文件中.或者,甚至更好,require_once他们那里,并把它们放在一个assets或includes主题的文件夹中.
-/theme/
-/includes/classes/class-studentsDatabase.php
-functions.php
Run Code Online (Sandbox Code Playgroud)
在functions.php中
define('TEMPLATE_PATH', get_template_directory());
require_once(TEMPLATE_PATH . '/includes/classes/class-studentsDatabase.php');
Run Code Online (Sandbox Code Playgroud)
您可以class将主题(es)作为一个整体实例化,或者根据需要在模板页面上实例化.
就安全性而言,我会避免将需要安全的数据库连接放在一个将要发送到外部的主题中.
我不确定我是否遵循了你正在做的事情,但如上所述,我会在主题环境之外处理这一点.
再一次,不知道你的用例,主题可以利用外部api,而api可以是wordpress wp-json api管理中心站点的数据库连接.
这将使该主题GET/ POST到端点(s)表示,手柄(S)认证和任何CRUD,并减轻了很多潜在的安全问题.然后外部站点上的主题只是解析返回的json,并且除此之外不会有任何DB访问.