【问题标题】:Laravel 4 Inversion of ControlLaravel 4 控制反转
【发布时间】:2013-11-24 04:23:43
【问题描述】:

我正在观看一段解释 laravel 的 IoC 容器基础知识的视频,但我无法理解这段代码在做什么。具体来说,我对UserRepository类的构造函数中的参数不太理解。我在 php 网站上找不到这种语法的示例,但运气不佳。

http://vimeo.com/53009943

<?php

 class UserRepository {

    protected $something;

    public function __construct(Something $something)

    {

        $this->something = $something;

    }
}

class Something {}

?>

【问题讨论】:

    标签: laravel laravel-4


    【解决方案1】:

    引用Laravel's documentation:

    IoC 容器可以通过两种方式解决依赖关系:通过 关闭回调或自动解析。

    但首先,什么是依赖项?在您发布的代码中,UserRepository 类有一个依赖项,即Something 类。这意味着UserRepository 将在其代码中的某处依赖Something。而不是直接使用它,通过做这样的事情

    $something = new Something;
    $something->doSomethingElse();
    

    它在其构造函数中被注入。这种技术被称为 dependency injection。所以,这些代码 sn-ps 会做同样的事情,不管有没有依赖注入。

    // Without DI
    class UserRepository {
    
        public function doSomething()
        {
            $something = new Something();
            return $something->doSomethingElse();
        }
    
    
    }
    

    现在,使用 DI,这与您发布的相同:

    // With DI
    class UserRepository {
    
        public function __construct(Something $something)
        {
            $this->something = $something;
        }
    
        public function doSomething()
        {
            return $this->something->doSomethingElse();
        }
    
    }
    

    您是说您不了解构造函数__constructor(Something $something)中传递的参数。该行告诉 PHP 构造函数需要一个参数 $something,它必须是 Something 类的实例。这被称为type hinting。传递不是Something(或任何子类)实例的参数将引发异常。


    最后,让我们回到 IoC 容器。我们之前说过,它的作用是解决依赖关系,它可以通过两种方式来实现。

    第一个,闭包回调:

    // This is telling Laravel that whenever we do
    // App::make('user.repository'), it must return whatever
    // we are returning in this function
    App::bind('UserRepository', function($app)
    {
        return new UserRepository(new Something);
    });
    

    第二个,自动解析

     class UserRepository {
    
        protected $something;
    
    
        public function __construct(Something $something)
    
        {
    
            $this->something = $something;
    
        }
    }
    
    // Now when we do this
    // Laravel will be smart enough to create the constructor
    // parameter for you, in this case, a new Something instance
    $userRepo = App::make('UserRepository');
    

    当使用接口作为构造函数的参数时,这特别有用并允许您的类更加灵活。

    【讨论】:

    • 很好的解释!我已经阅读了一段时间,试图了解它是如何工作的。现在这更有意义了……我还是 PHP 框架的新手,laravel 是我的第一个!
    • 如果所有这些概念现在听起来很奇怪,请不要担心。当你变得更有经验时,它们会变得清晰。我们都去过那里;)
    猜你喜欢
    • 2013-06-10
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 2013-08-26
    • 2014-03-18
    • 2013-06-24
    • 1970-01-01
    • 2015-01-15
    相关资源
    最近更新 更多