(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)控制器层使用
原文链接:https://www.f2er.com/javaschema/284307.html<?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; }