laravel的依赖注入

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gaoxuaiguoyi/article/details/50042829
首先创建service层的接口类,和实现类。在app文件夹下面创建services文件夹。
(1)接口类:
<?php

namespace App\Services;
use App\models\Users;

  interface IUserService{

   /**
    * 获取用户数据
    * [getUserLists description]
    * @return [type] [description]
    */
   public function getUserLists();
   /**
    * 添加用户
    */
   public function addUser(Users $user);
   /**
    * 删除用户
    */
   public function deleteUser(Users $user);
   /**
    * 查找用户
    */
   public function findUser(int $id);

  }
?>


(2)实现类:
<?php
 namespace App\Services;
 // use App\Services\IUserService;
 use App\models\Users;
   class IUserServiceImpl implements IUserService{

     /**
      * 获取用户列表
      * [getUserLists description]
      * @return [type] [description]
      */
     public function getUserLists(){


            return Users::all()->toArray();
     }
     /**
      * 添加用户
      * [addUser description]
      * @param Users $user [description]
      */
     public function addUser(Users $user){

     }
     /**
      * [deleteUser description]
      * @param  Users  $user [description]
      * @return [type]       [description]
      */
     public function deleteUser(Users $user){

     }
     /**
      * 根据用户id查询用户
      * [findUser description]
      * @param  int    $id [description]
      * @return [type]     [description]
      */
     public function findUser(int $id){

     }
   }
?>


(3)配置依赖注入
在Providers文件夹下面的AppServiceProvider中配置一下IOC
   public function register()
    {        
        //$this->app->bind(App\Services\IUserService::class, App\Services\IUserServiceImpl::class);
    //单例模式创建对象
        $this->app->singleton('\App\Services\IUserService', function()
                {
                    return new \App\Services\IUserServiceImpl();
                });
    }


(4)控制器层使用
<?php
namespace App\Http\Controllers;    
use App\Http\Controllers\Controller;
use App\Repositories\UserRepository;
use App\models\Users;
use Cache;
use Log;
use Event;
use App\Services\IUserService;
use App\Events\PupUserchange;
/**
 * 控制器
 */
class UserController extends Controller{
 private  $UserService;
//注入接口的实例对象IUserServiceImpl,其实laravel框架帮助我们实现了 IUserService  $service = new IUserServiceImpl();这一步。
 public function __construct(IUserService $service){
 
  $this->UserService = $service;

 }


没有更多推荐了,返回首页