Skip to content

Commit b8459da

Browse files
committed
service repository
1 parent 434ddef commit b8459da

File tree

4 files changed

+98
-0
lines changed

4 files changed

+98
-0
lines changed

app/Repository/IRepository.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
namespace App\Repository;
5+
6+
7+
use App\Model\Model;
8+
9+
/**
10+
* @template T of Model
11+
* @property T $model
12+
*/
13+
abstract class IRepository
14+
{
15+
/**
16+
* @return null|T
17+
*/
18+
public function getById($id)
19+
{
20+
return $this->model->newQuery()->find($id);
21+
}
22+
23+
public function __construct()
24+
{
25+
$this->setModel();
26+
}
27+
28+
abstract function setModel(): void;
29+
}

app/Repository/UserRepository.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
namespace App\Repository;
5+
6+
use App\Model\User;
7+
8+
/**
9+
* @extends IRepository<User>
10+
*/
11+
class UserRepository extends IRepository
12+
{
13+
14+
function setModel(): void
15+
{
16+
$this->model = new User();
17+
}
18+
}

app/Service/IService.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
namespace App\Service;
5+
6+
7+
use App\Repository\IRepository;
8+
9+
/**
10+
* @template T
11+
* @property IRepository<T> $repository
12+
*/
13+
abstract class IService
14+
{
15+
public function __construct()
16+
{
17+
$this->repository = $this->repository();
18+
}
19+
/**
20+
* @return T|null
21+
*/
22+
public function getById($id)
23+
{
24+
return $this->repository->getById($id);
25+
}
26+
27+
/**
28+
* @return IRepository<T>
29+
*/
30+
abstract protected function repository();
31+
}

app/Service/UserService.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
namespace App\Service;
5+
6+
use App\Repository\IRepository;
7+
use App\Repository\UserRepository;
8+
use function App\Kernel\di;
9+
10+
/**
11+
* @extends IService<UserRepository>
12+
*/
13+
final class UserService extends IService
14+
{
15+
16+
protected function repository()
17+
{
18+
return di(UserRepository::class);
19+
}
20+
}

0 commit comments

Comments
 (0)