我正在尝试使用PHP中的OOP构建站点.每个人都在谈论Singleton,hermetization,MVC和使用异常.所以我试图这样做:
全班课堂建设:
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();
}
我不喜欢那些异常处理程序-我不想像一些宠物小精灵一样抓住它们…我想简单地使用一些东西:
$core-> theme-> display(‘footer’);
如果出现问题,并且启用了调试模式,则应用程序显示错误.我该怎么办?
解决方法:
我对PHP不熟悉,但是您一定要停止执行pokemon异常.首先,应该不需要将每个异常(PDOException)替换为特定的异常(CoreException).其次,在用法部分中使用多个catch块,如下所示:
try
{
$core->theme->display('footer');
}
catch(ThemeException $e)
{
echo $e->getMessage();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
然后,您的“核心”课程可以大大缩减(不再需要为每个项目尝试/抓住).当然,您将在更高级别上显示更多catch块,但这就是您应该对OOP和异常执行的操作.
最后,检查要尝试捕获的异常的某些子集是否已经存在异常超类.这将减少捕获块的数量.