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 中国語 Web サイトの他の関連記事を参照してください。

Laravelは、直感的なフラッシュメソッドを使用して、一時的なセッションデータの処理を簡素化します。これは、アプリケーション内に簡単なメッセージ、アラート、または通知を表示するのに最適です。 データは、デフォルトで次の要求のためにのみ持続します。 $リクエスト -

PHPクライアントURL(CURL)拡張機能は、開発者にとって強力なツールであり、リモートサーバーやREST APIとのシームレスな対話を可能にします。尊敬されるマルチプロトコルファイル転送ライブラリであるLibcurlを活用することにより、PHP Curlは効率的なexecuを促進します

Laravelは簡潔なHTTP応答シミュレーション構文を提供し、HTTP相互作用テストを簡素化します。このアプローチは、テストシミュレーションをより直感的にしながら、コード冗長性を大幅に削減します。 基本的な実装は、さまざまな応答タイプのショートカットを提供します。 Illuminate \ support \ facades \ httpを使用します。 http :: fake([[ 'google.com' => 'hello world'、 'github.com' => ['foo' => 'bar']、 'forge.laravel.com' =>

PHPロギングは、Webアプリケーションの監視とデバッグ、および重要なイベント、エラー、ランタイムの動作をキャプチャするために不可欠です。システムのパフォーマンスに関する貴重な洞察を提供し、問題の特定に役立ち、より速いトラブルシューティングをサポートします

顧客の最も差し迫った問題にリアルタイムでインスタントソリューションを提供したいですか? ライブチャットを使用すると、顧客とのリアルタイムな会話を行い、すぐに問題を解決できます。それはあなたがあなたのカスタムにより速いサービスを提供することを可能にします

記事では、PHP 5.3で導入されたPHPの後期静的結合(LSB)について説明し、より柔軟な継承を求める静的メソッドコールのランタイム解像度を可能にします。 LSBの実用的なアプリケーションと潜在的なパフォーマ

この記事では、フレームワークにカスタム機能を追加し、アーキテクチャの理解、拡張ポイントの識別、統合とデバッグのベストプラクティスに焦点を当てています。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

MantisBT
Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

MinGW - Minimalist GNU for Windows
このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

SublimeText3 英語版
推奨: Win バージョン、コードプロンプトをサポート!

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ホットトピック



