1. Go to this page and download the library: Download gohari/repository-pattern library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
namespace App\Repositories;
use Gohari\RepositoryPattern\BaseRepository;
use App\Models\User;
use App\Repositories\Contracts\UserRepositoryInterface;
class UserRepository extends BaseRepository implements UserRepositoryInterface
{
public function __construct(User $user)
{
parent::__construct($user);
}
}
class User extends Model
{
protected $fillable = ['name', 'age', 'is_active', 'settings'];
protected $casts = [
'age' => 'integer',
'is_active' => 'boolean',
'settings' => 'array',
];
}
public function register(): void
{
$this->app->bind(
\App\Repositories\Contracts\UserRepositoryInterface::class,
\App\Repositories\UserRepository::class
);
}
use App\Repositories\Contracts\UserRepositoryInterface;
class UserService
{
public function __construct(
private readonly UserRepositoryInterface $users
) {
}
public function activeUsers()
{
return $this->users
->query()
->where('is_active', true)
->get();
}
}
use Gohari\RepositoryPattern\BaseRepositoryInterface;
interface UserRepositoryInterface extends BaseRepositoryInterface
{
public function findByEmail(string $email);
}
use App\Models\User;
use App\Repositories\Contracts\UserRepositoryInterface;
use Gohari\RepositoryPattern\BaseRepository;
class UserRepository extends BaseRepository implements UserRepositoryInterface
{
public function __construct(User $user)
{
parent::__construct($user);
}
public function findByEmail(string $email)
{
return $this->query()->where('email', $email)->first();
}
}