【发布时间】:2017-06-23 22:56:34
【问题描述】:
我正在设计我的第一个 Web 应用程序,我正在寻找一些关于如何在其中实施 oop 原则的建议。
基本上,该应用由许多使用 Jquery ajax 填充选项的级联下拉选择组成,以便构建 sql 语句以返回一组特定的数据(包括执行一些计算)。
到目前为止,我构建它的方式是脚本标记中的许多 JS 函数,用于带有相应事件处理程序的 ajax 调用。例如:
$('#show_result').on('click', getResult);
function getResult() {
alert( "Results displayed" );
$.ajax(
{
url: "calc_php/get_results.php",
success: function(result)
{
$("#texty").html(result);
}
});
}
然后是一些php包含文件,例如:
<?php
include '../../database.php';
$pdo = Database::connect();
$sql = 'SELECT * FROM country ORDER BY country_id;';
foreach ($pdo->query($sql) as $row) {
echo '<option value="'.$row['country_id'].'">'.$row['descrp'].'</option>';
}
Database::disconnect();
?>
我知道对于这么小的应用程序,oop 可能不是必需的,但是有兴趣学习,谁能建议我在这方面使用 oop 的方向?我唯一模糊的一点是数据库连接类:
<?php
class Database
{
private static $dbName = 'web_app' ;
private static $dbHost = 'localhost' ;
private static $dbUsername = 'root';
private static $dbUserPassword = '**NotThatStupid**';
private static $cont = null;
public function __construct() {
die('Init function is not allowed');
}
public static function connect()
{
// One connection through whole application
if ( null == self::$cont )
{
try
{
self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);
}
catch(PDOException $e)
{
die($e->getMessage());
}
}
return self::$cont;
}
public static function disconnect()
{
self::$cont = null;
}
}
?>
我们将不胜感激地收到任何建议或指点! :)
【问题讨论】:
-
综合了 PHP 和 JavaScript 的通用 OOP 教程有点超出了 SO 的范围。
-
赞赏 - 对不起我的第一个问题。虽然,公平地说,我不是在寻找教程,只是一些关于从这里去哪里的指示:)
-
SoftwareEngineering.SE 可能是合适的,和/或您可以在元中搜索where to ask
-
@StephenP 在引用其他网站时,指出cross-posting is frowned upon 通常会有所帮助(写下这个问题,在那里它可能会作为Are there any OO-principles that are practically applicable for Javascript? 的副本被关闭)
标签: javascript php ajax oop web