【发布时间】:2018-10-21 20:54:51
【问题描述】:
我有以下抽象类,它具有Entity 对象的参数和返回类型声明。 Entity 是一个虚构的占位符,实际上应该声明它们以显示返回 User(或扩展 EntityServices 指定的任何实际类)。
是否可以让EntityServices 使用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;
}
}
【问题讨论】:
-
Is this possible? 什么应该是可能的? -
不清楚你想要什么。
-
我将编辑原始范围以更好地描述。谢谢
-
@GabrielHeming 我不这么认为。我希望使扩展父抽象类中的方法更窄,并匹配扩展子类的方法。
标签: php oop type-hinting