如何使用Laravel自动注入依赖关系

时间:2017-03-31 16:43:24

标签: php laravel lumen

我正在尝试构建一个在流明上使用依赖注入的结构。

我有一个服务层和存储库层。

我想将存储库层注入服务层。让我试着向您展示代码

    interface IUserRepostitory {
        public function getByID($id);
    }

    class UserRepository extends BaseRepository implements IRepository{
        public function getByID($id) {
            //Please don't think how this function works, my question about dependency injection
            return $this->findOrFail($id);
        }

    }


   interface IService {
       public function getByID($id);
   }

   class UserService implements IService{

       private $Repository;
       public __construct(IUserRepositor $UserRepository) {
            $this->Repository = $UserRepository
       }

       public function getByID($id) {
             return $this->Repository->getByID($id);
       }
   }

我在这里注册依赖项解析器。

//Dependency resolver for Repository Layer
class RepositoryServiceProvider extends ServiceProvider {

    public function register()
    {
        $this->app->singleton(IUserRepository::class, function () {
            return new UserRepository();
        });
    }

}

我在这里注册服务层

class ServiceServiceProvider extends ServiceProvider {

    public function register()
    {
        $this->app->singleton(IUserService::class, function () {
            //Here is what I don't like
            //It would be great a solution that automaticly resolve UserRepository.
            return new UserService(new UserRepository());
        });
    }
}

如您所见,我想自动将依赖关系解析为UserService。但是单例方法需要创建返回对象。

有更好的方法吗?

***注意:请不要注意语法,我是在流明上写的,但在laravel上也是一样的问题。

1 个答案:

答案 0 :(得分:1)

<RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="10dp" android:paddingBottom="10dp"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="horizontal"> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/checkBox" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World"/> </LinearLayout> </RelativeLayout> 绑定到UserRepository后,您可以通过使用IUserRepository函数解析IUserService并使用IUserRepository实例化!

修改make

ServiceServiceProvider