laravel的依赖注入

首先创建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;

 }

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...