依赖注入 - 不能使用Closure类型的对象作为数组

时间:2017-01-23 09:57:38

标签: php oop dependency-injection

我正在尝试在我的应用程序中集成一个简单的依赖注入设计模式,因为它很小。这是班级:

class Factory
{
    private static $_models = array();

    public static function set(
        $callback,
        $controller,
        $args = array()
    ) {
        if( is_callable( $controller ) ) {
            // store the controller and args to the array key callback
            self::$_models[$callback] = array(
                'args' => $args,
                'controller' => $controller
            );
            return;
        }
        // if the controller isn't a function return
        throw new Exception("Undefined Closure.");
    }

    public static function get(
        $callback,
        $action
    ) {
        if(self::$_models[$callback]) {
            // execute the closure to receive controller array
            $prefix = call_user_func(self::$_models[$callback]['controller']);
            if(is_callable($prefix[$action])) {
                // execute the closure with or without args
                return count($prefix['args']) < 0 ? $prefix[$action]($prefix['args']) : $prefix[$action]();
            }
            // couldn't find the function so return an error
            throw new Exception("Undefined action: $action.");
        }
        // couldn't find the callback so return an error
        throw new Exception("Undefined callback: $callback.");
    }
}

当我尝试设置这样的控制器时:

Factory::set('example', function($arg) {
    return array(
        'controller' => function() {
             global $arg;
             return $arg;
         }
    );
}, array('value'));

我收到此错误:

  

未捕获错误:无法使用Closure类型的对象作为数组

代码没有达到这个部分:

print_r(Factory::get('example', 'controller')); // expected output array: 'value'

0 个答案:

没有答案