我正在尝试在 PHP 中使用 OOP 构建网站。每个人都在谈论 Singleton、hermetization、MVC 和使用异常。所以我试着这样做:
类 build 整个网站:
class Core
{
public $is_core;
public $theme;
private $db;
public $language;
private $info;
static private $instance;
public function __construct($lang = 'eng', $theme = 'default')
{
if(!self::$instance)
{
try
{
$this->db = new sdb(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
}
catch(PDOException $e)
{
throw new CoreException($e->getMessage());
}
try
{
$this->language = new Language($lang);
}
catch(LangException $e)
{
throw new CoreException($e->getMessage());
}
try
{
$this->theme = new Theme($theme);
}
catch(ThemeException $e)
{
throw new CoreException($e->getMessage());
}
}
return self::$instance;
}
public function getSite($what)
{
return $this->language->getLang();
}
private function __clone() { }
}
类管理主题
class Theme
{
private $theme;
public function __construct($name = 'default')
{
if(!is_dir("themes/$name"))
{
throw new ThemeException("Unable to load theme $name");
}
else
{
$this->theme = $name;
}
}
public function getTheme()
{
return $this->theme;
}
public function display($part)
{
if(!is_file("themes/$this->theme/$part.php"))
{
throw new ThemeException("Unable to load theme part: themes/$this->theme/$part.php");
}
else
{
return 'So far so good';
}
}
}
和用法:
error_reporting(E_ALL);
require_once('config.php');
require_once('functions.php');
try
{
$core = new Core();
}
catch(CoreException $e)
{
echo 'Core Exception: '.$e->getMessage();
}
echo $core->theme->getTheme();
echo "<br />";
echo $core->language->getLang();
try
{
$core->theme->display('footer');
}
catch(ThemeException $e)
{
echo $e->getMessage();
}
我不喜欢那些异常处理程序——我不想像捕捉一些口袋妖怪一样捕捉它们……我想使用简单的东西: $核心->主题->显示('页脚'); 如果出现问题,并且启用了 Debug模式,则应用程序会显示错误。我该怎么办?
最佳答案
我不熟悉 PHP,但您绝对应该停止执行 pokemon 异常。首先,应该没有必要用特定异常 (CoreException) 替换每个异常 (PDOException)。其次,在您的使用部分使用多个 catch block ,如下所示:
try
{
$core->theme->display('footer');
}
catch(ThemeException $e)
{
echo $e->getMessage();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
然后您的“核心”类可以大大缩小(每个项目不再尝试/捕获)。诚然,您将在更高级别显示更多 catch block ,但这是您应该使用 OOP 和异常执行的操作。
最后,检查您要捕获的某些异常子集是否已经存在异常父类(super class)。这将减少 catch block 的数量。
关于php - 异常困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2888461/