通过php反射机制我们可以实现栏目的动态扩从
1.文件夹目录
2.通过定义一个plugin接口
<?php
interface IPlugin {
static function getName();
static function init();
static function getMenu();
}
?>
3.让不同类目文件实现此方法
<?php
class adv implements IPlugin {
public static function init() {
echo "初始化adv菜单";
}
public static function getName() {
return 'adv菜单 ';
}
public static function getMenu() {
return array (
'href' => 'http://www.sina.com',
'name' => 'adv菜单'
);
}
}
<?php
class look implements IPlugin {
public static function init() {
echo "初始化look菜单";
}
public static function getName() {
return 'look菜单 ';
}
public static function getMenu() {
return array (
'href' => 'http://www.baidu.com',
'name' => 'look菜单'
);
}
}
<?php
class welcome implements IPlugin {
public static function init() {
echo "初始化welcome菜单";
}
public static function getName() {
return 'welcome菜单 ';
}
public static function getMenu() {
return array (
'href' => 'http://www.welcome.com',
'name' => 'welcome菜单'
);
}
}
3.通过反射显示这些栏目
<?php
include dirname ( __FILE__ ) . "/interface/IPlugin.php";
$menu [] = array (
'href' => 'http://www.jiukuaiyou.com',
'name' => '首页'
);
function autoLoadClass() {
$path = dirname ( __FILE__ ) . '/plugin/';
$handledir = opendir ( $path );
while ( ($file = readdir ( $handledir )) !== false ) {
if ($file != "." && $file != ".." && is_file ( $path . $file )) {
$classfileArr [] = $path . $file;
}
}
if (count ( $classfileArr ) > 0) {
foreach ( $classfileArr as $classfile ) {
include $classfile;
}
}
}
function autoLoadMenu() {
global $menu;
foreach ( get_declared_classes () as $class ) {
$refclass = new ReflectionClass ( $class );
if ($refclass->implementsInterface ( "IPlugin" )) {
$refclass->getMethod ( "getName" )->invoke ( null );
$menuItem = $refclass->getMethod ( "getMenu" )->invoke ( null );
$menu = array_merge ( $menu, array (
$menuItem
) );
}
}
}
autoLoadClass ();
autoLoadMenu ();
foreach ( $menu as $m ) {
echo "<a href='" . $m ['href'] . "'>" . $m ['name'] . "</a> ";
}