您现在的位置是:自如初>LaravelLaravel

Laravel 使用 Server 层

温新 2022-12-11 19:00:50 Laravel 397人已围观

简介Laravel Server 层,从控制器中分离一层,代码更加容易维护可读

hi,我是温新,一名 PHPer


将所有代码写在控制器中,这并不是一个很好的方法。可以使用 Server 层将代码进行分离,分离后的代码逻辑更加清晰而且的方法还能进行复用。


1、创建控制器

php artisan make:controller Test/TestController

2、创建 TestServer.php

app 目录下创建该层: Test/TestService.php

<?php

namespace App\Service\Test;

class TestService
{
}

3、定义路由

// routes/web.php
<?php

use App\Http\Controllers\Test\TestController;
use Illuminate\Support\Facades\Route;

Route::get('tests', [TestController::class, 'index']);

4、编写 TestService.php 代码

<?php

namespace App\Service\Test;

use App\Models\User;

class TestService
{
   public function getUserList()
   {
       return User::all();
   }
}

5、使用 TestService.php


对于 Service 层的使用,给出两种使用方法,一种是使用 new 实例出一个对象;另一种通过绑定服务者来使用。


通过 new 对象来使用:TestController.php 代码如下:

<?php

namespace App\Http\Controllers\Test;

use App\Http\Controllers\Controller;
use App\Service\Test\TestService;
use Illuminate\Http\Request;

class TestController extends Controller
{
   public function index()
   {
       $userService = new TestService();
       return $userService->getUserList();
   }
}

通过绑定服务提供者来使用


注册服务

<?php
// app/Providers/AppServiceProvier.php
namespace App\Providers;

use App\Service\Test\TestService;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
   public function register()
   {
       // 使用单例注册 Service 层服务
       $this->app->instance(TestService::class, new TestService)
   }
}

控制器中使用服务

<?php

namespace App\Http\Controllers\Test;

use App\Http\Controllers\Controller;
use App\Service\Test\TestService;
use Illuminate\Http\Request;

class TestController extends Controller
{
   public function index()
   {
       return app(TestService::class)->getUserList();
   }
}


很赞哦!(2)

文章评论

登录 注册

自如初--时间轴

QQ登录

站名:自如初

独白:向前走!向前走!

邮箱:ziruchu@qq.com

站点信息