У меня есть следующий абстрактный класс, у которого есть аргументы и объявления типа возврата объекта Entity
.Entity
является вымышленным заполнителем, и в действительности они должны быть объявлены как возвращающие User
(или независимо от того, какой фактический класс, который указывает EntityServices
указывает).
Возможно ли использовать EntityServices
useобъявления типов User
вместо Entity
без дублирования скрипта в классе User
?Если так, то как?Если нет, существует ли обходной путь, позволяющий повторно использовать сценарий, по крайней мере, с некоторым уровнем функциональности объявления типа?
<?php
namespace NotionCommotion;
abstract class EntityService
{
//Constructor in child
public function get(int $id): ?Entity {
//Will return User or Bla argument based on the extending class
return $this->mapper->read($id);
}
public function create(array $data): Entity {
//Will return User or Bla argument based on the extending class
if (!$this->validator->load($this->getValidationFile())->isValid($data)) throw new UserValidationError($this->validator, $data);
$this->doTransation(function(){$this->mapper->add($data);});
}
public function update(array $data, int $id): Entity {
//Will return User or Bla argument based on the extending class
if (!$this->validator->load($this->getValidationFile())->nameValueisValid($data)) throw new UserValidationError($this->validator, $data);
$this->doTransation(function(){$this->mapper->update($data);});
}
public function delete(int $id): void {
$this->mapper->delete($id);
}
public function whatever(Entity $whatever) {
//Requires User or Bla argument based on the extending class
}
protected function doTransation($f){
try {
$f();
$this->pdo->commit();
} catch (\PDOException $e) {
$this->pdo->rollBack();
throw($e);
}
}
abstract protected function getValidationFile();
}
Класс UserServices
<?php
namespace NotionCommotion\User;
class UserService extends \EntityService
{
public function __construct(UserMapper $userMapper, \Validator $validator, Foo $foo) {
$this->mapper=$userMapper;
$this->validator=$validator;
$this->foo=$foo;
}
}
Класс BlaServices
<?php
namespace NotionCommotion\Bla;
class BlaService extends \EntityService
{
public function __construct(BlaMapper $blaMapper, \Validator $validator) {
$this->mapper=$blaMapper;
$this->validator=$validator;
}
}