Here's a cheat sheet on how to make your simple service class more useful by adding dependency injection, a facade, and a way to easily swap in a fake.
The skeleton is simple:
- The original service class
- Create a contract the service class abides by
- In a service provider, register the service class in the container
- Create a facade
- Create a fake implementation of the contract that can be swapped for testing
The original service class
Here's our original service class that we are starting with (apologies for not having a compelling example, but it isn't really necessary to contrive one for this).
<?php namespace App\Foo; class FooService { public function foo(): string { return 'bar'; } public function fizz(): string { return 'buzz'; } }
The contract
First, we should create a contract so we can ensure that our eventual fake and our original service both meet expectations. As well as any future implementations.
<?php namespace App\Foo\Contracts; interface Foo { public function foo(): string; public function fizz(): string; }
Don't forget to make sure the service implements it.
<?php namespace App; use App\Foo\Contracts\Foo; class FooService implements Foo { // ... }
Binding to the container
Next, we should bind the concrete implementation to the contract in our service provider.
<?php namespace App\Providers; use App\Foo\Contracts\Foo; use App\FooService; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Register any application services. */ public function register(): void { $this->app->bind(Foo::class, FooService::class); } // ... }
The facade
Now, we can create our facade class.
<?php namespace App\Foo\Facades; use Illuminate\Support\Facades\Facade; /** * @method static string foo(): string * @method static string fizz(): string */ class Foo extends Facade { protected static function getFacadeAccessor(): string { return \App\Foo\Contracts\Foo::class; } }
The facade simply needs the name of the binding it will pull from the container to be returned from getFacadeAccessor. In our case, that's the name of the contract that currently has our service bound to it.
Note that if you want IDE support, you'll have to re-define the method signatures in the doc block above the class.
At this point, we can use our facade.
Usage
<?php namespace App\Http\Controllers; use App\Foo\Facades\Foo; class FooController extends Controller { public function index() { return response()->json([ 'foo' => Foo::foo(), ]); } }
Alternatively, we can also inject it as a dependency.
<?php namespace App\Http\Controllers; use App\Foo\Contracts; class FooController extends Controller { public function __construct(protected Foo $foo) {} public function index() { return response()->json([ 'foo' => $this->foo->foo(), ]); } }
Faking the facade
Laravel often offers a neat way to easily fake its facades, e.g. Event::fake(). We can implement this ourselves.
All we have to do is create the fake implementation of our contract, then add the fake method to our facade.
<?php namespace App\Foo; use App\Foo\Contracts\Foo; class FakeFooService implements Foo { public function __construct(public Foo $actual) {} public function foo(): string { return 'fake'; } public function fizz(): string { return 'very fake'; } }
In our fake implementation, we also create a public reference to the "actual" concrete class.
And here is our facade fake implementation. You can see we utilize that reference to actual.
<?php namespace App\Foo\Facades; use App\Foo\FakeFooService; use Illuminate\Support\Facades\Facade; /** * @method static string foo(): string * @method static string fizz(): string */ class Foo extends Facade { public static function fake() { $actual = static::isFake() ? static::getFacadeRoot()->actual : static::getFacadeRoot(); tap(new FakeFooService($actual), function ($fake) { static::swap($fake); }); } // ... }
A basic test
Now let's write a quick test that hits the controller example we created above.
<?php namespace Tests\Feature; use App\Foo\Facades\Foo; use Illuminate\Testing\Fluent\AssertableJson; use Tests\TestCase; class FooTest extends TestCase { public function test_foo(): void { $response = $this->get('/'); $response->assertJson(fn (AssertableJson $json) => $json->where('foo', 'bar')); } public function test_fake_foo(): void { Foo::fake(); $response = $this->get('/'); $response->assertJson(fn (AssertableJson $json) => $json->where('foo', 'fake')); } }
The tests are not useful but they show how easy it is to use our fake. In test_fake_foo we get foo=fake while test_foo returns foo=bar.
Taking testing further
The fun thing about fakes is that in our fake implementation, we can add extra methods to test anything we may find useful. For example, we could slap a counter in our fake's foo method that increments every time we call foo. Then we could add a method called assertFooCount where we can assert that the method was called as many times as we are expecting.
<?php namespace App\Foo; use App\Foo\Contracts\Foo; use Illuminate\Testing\Assert; class FakeFooService implements Foo { public int $fooCount = 0; public function __construct(public Foo $actual) {} public function foo(): string { $this->fooCount++; return 'fake'; } public function fizz(): string { return 'very fake'; } public function assertFooCount(int $count) { Assert::assertSame($this->fooCount, $count); } }
As you can see we use Laravel's Illuminate\Testing\Assert to make the assertion. Then our test can look like this.
public function test_incrementor(): void { Foo::fake(); Foo::foo(); Foo::foo(); Foo::foo(); Foo::assertFooCount(3); // pass! }
That's it!
Not everything needs a facade, but when you are building tools/packages that are used internally, a facade is often a strong pattern to rely upon.
Here's the repo with all the code: https://github.com/ClintWinter/laravel-facade-example
위 내용은 Laravel에서 테스트 가능한 외관 만들기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Laravel은 직관적 인 플래시 방법을 사용하여 임시 세션 데이터 처리를 단순화합니다. 응용 프로그램에 간단한 메시지, 경고 또는 알림을 표시하는 데 적합합니다. 데이터는 기본적으로 후속 요청에만 지속됩니다. $ 요청-

PHP 클라이언트 URL (CURL) 확장자는 개발자를위한 강력한 도구이며 원격 서버 및 REST API와의 원활한 상호 작용을 가능하게합니다. PHP CURL은 존경받는 다중 프로모토콜 파일 전송 라이브러리 인 Libcurl을 활용하여 효율적인 execu를 용이하게합니다.

Laravel은 간결한 HTTP 응답 시뮬레이션 구문을 제공하여 HTTP 상호 작용 테스트를 단순화합니다. 이 접근법은 테스트 시뮬레이션을보다 직관적으로 만들면서 코드 중복성을 크게 줄입니다. 기본 구현은 다양한 응답 유형 단축키를 제공합니다. Illuminate \ support \ Facades \ http를 사용하십시오. http :: 가짜 ([ 'google.com'=> 'Hello World', 'github.com'=> [ 'foo'=> 'bar'], 'forge.laravel.com'=>

고객의 가장 긴급한 문제에 실시간 인스턴트 솔루션을 제공하고 싶습니까? 라이브 채팅을 통해 고객과 실시간 대화를 나누고 문제를 즉시 해결할 수 있습니다. 그것은 당신이 당신의 관습에 더 빠른 서비스를 제공 할 수 있도록합니다.

PHP 로깅은 웹 애플리케이션을 모니터링하고 디버깅하고 중요한 이벤트, 오류 및 런타임 동작을 캡처하는 데 필수적입니다. 시스템 성능에 대한 귀중한 통찰력을 제공하고 문제를 식별하며 더 빠른 문제 해결을 지원합니다.

기사는 PHP 5.3에 도입 된 PHP의 LSB (Late STATIC BING)에 대해 논의하여 정적 방법의 런타임 해상도가보다 유연한 상속을 요구할 수있게한다. LSB의 실제 응용 프로그램 및 잠재적 성능

이 기사에서는 프레임 워크에 사용자 정의 기능 추가, 아키텍처 이해, 확장 지점 식별 및 통합 및 디버깅을위한 모범 사례에 중점을 둡니다.

Alipay PHP ...


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

Dreamweaver Mac版
시각적 웹 개발 도구

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.
