0

我正在使用这个问题中的 Dependency Class PHP dependency class我正在使用特别是 Paul Norman 的版本,它工作得几乎完美,但我发现订单并不总是正确的

您可以在此处查看代码http://codepad.org/EBtWWn1b

结果不对,应该是

已加载:数组
(
    [0] => 菜单
    [1] => 设置
    [2] => 国家
    [3] => 仪表板
    [4] => 语言
    [5] => 模块
    [6] => 用户
)
失败:数组
(
)

你知道有什么方法可以解决吗?

谢谢 !

4

1 回答 1

2

关于 Paul Norman 的解决方案,我不知道该告诉您什么,但似乎有一个错误......我尝试了一个解决方案,它似乎满足了您示例中的依赖关系(尽管没有完全列出它们你想要的顺序...)

class Dependencies
{
    private $items;
    private $depends;
    private $hasDependency;

    public function __construct()
    {
        $this->items = array();
        $this->depends = array();
        $this->hasDependency = array();
    }

    public function add($item, $dependsOn = array())
    {
        $this->items[] = $item;
        foreach ($dependsOn as $dependsOnItem)
        {
            $this->items[] = $dependsOnItem;
            $this->depends[$dependsOnItem][] = $item;
        }

        $this->items = array_unique($this->items);
        $this->hasDependency[$item] = $dependsOn;
    }

    public function getLoadOrder()
    {
        $order = array();

        $hasChanged = true;
        while (count($order) < count($this->items) && $hasChanged === true)
        {
            $hasChanged = false;
            foreach ($this->hasDependency as $item => $dependencies)
            {
                if ($this->satisfied($item, $order))
                {
                    $order[] = $item;
                    unset($this->hasDependency[$item]);
                    $hasChanged = true;
                }
            }
        }

        if (count($order) < count($this->items) && $hasChanged === false)
        {
            echo 'Impossible set of dependencies';
            return false;
        }

        return $order;
    }

    private function satisfied($item, $addedSoFar)
    {
        $dependencies = $this->hasDependency[$item];

        foreach ($dependencies as $dependency)
        {
            if (!in_array($dependency, $addedSoFar))
            {
                return false;
            }
        }

        return true;
    }
}

$deps = new Dependencies();

$deps->add('countries', array('menus', 'settings'));
$deps->add('dashboard', array('menus'));
$deps->add('languages', array('menus', 'settings'));
$deps->add('menus');
$deps->add('modules'  , array('menus'));
$deps->add('settings' , array('menus'));
$deps->add('users'    , array('menus'));

print_r($deps->getLoadOrder());
于 2012-09-10T04:45:07.727 回答