Skip to content

Instantly share code, notes, and snippets.

@deleugpn
Last active June 29, 2019 16:35
Show Gist options
  • Save deleugpn/7a2adaee968c0a73b6c6edafb3ffbdd3 to your computer and use it in GitHub Desktop.
Save deleugpn/7a2adaee968c0a73b6c6edafb3ffbdd3 to your computer and use it in GitHub Desktop.
<?php
class RemoveUserTest extends DatabaseTestCase
{
protected function setUp(): void
{
parent::setUp();
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email');
$table->timestamps();
});
}
public function test_remove_user()
{
User::query()->create([
'name' => 'Taylor Otwell',
'email' => 'test@laravel.com',
]);
$service = new MyService();
$service->remove(User::query()->first());
$this->assertDatabaseMissing('users', [
'email' => 'test@laravel.com',
]);
}
}
class User extends Model
{
protected $guarded = [];
protected $table = 'users';
}
class MyService
{
public function remove(User $user)
{
$user->delete();
}
}
<?php
class RemoveUserTest extends DatabaseTestCase
{
protected function setUp(): void
{
parent::setUp();
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email');
$table->timestamps();
});
}
public function test_remove_user()
{
User::query()->create([
'name' => 'Taylor Otwell',
'email' => 'test@laravel.com',
]);
$service = new MyService();
$service->remove(User::query()->first());
$this->assertDatabaseMissing('users', [
'email' => 'test@laravel.com',
]);
}
public function test_remove_all_users()
{
User::query()->create([
'name' => 'Taylor Otwell',
'email' => 'test@laravel.com',
]);
User::query()->create([
'name' => 'Marco Deleu',
'email' => 'marco@deleu.dev',
]);
$service = new MyService;
$service->remove(new User);
self::assertSame(0, User::query()->count());
}
}
class User extends Model
{
protected $guarded = [];
protected $table = 'users';
}
class MyService
{
public function remove(User $user)
{
$user->newQuery()->delete();
}
}
@deleugpn
Copy link
Author

Eloquent type-hint has effectively two meanings: A Repository-type class that can communicate with the database or a specific row. When sending an Eloquent object as a repository, the receiver can use Eloquent to do all sorts of database operation. However, when the intent is to specify a single instance of a record, the receiver can still "disobey" that intent. In the following snippet, the 2nd version was developed by a Jr. Developer that thought he could reuse an existing service without realizing that he would be changing the intended type of object the service was suppose to receive WITHOUT breaking any test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment