验证构造函数中的参数

时间:2019-07-13 17:21:03

标签: php oop

我正在开发一个图书馆管理系统,基本上,我有一个抽象类“阅读器”,它扩展到“学生,教师和一般人”。我的问题是,我有一个“ Requests”类,我需要知道哪个“ Reader”请求该书,才能验证此数据:

“老师只能同时要求10本书,学生只能同时要求5本书​​,而公众一般可以同时要求2本书;”

“老师每本书最多可以保留6个月,学生最多可以保留5天,公众最多可以保留1个月;”

“如果老师有一本书超过三个月,并且有必要提出要求,则必须通知老师退还这本书;”

如何在__construct中传递三种类型的“阅读器”,以验证上述数据。

class Requests
{
    protected $bookRequested;
    protected $teacher;
    protected $student;
    protected $public;
    protected $requestDate;
    protected $returnDate;

    public function __construct(Book $bookRequested, Teacher $teacher, Student $student, GeneralPublic $public)
    {
        $this->bookRequested = $bookRequested;
        $this->teacher = $teacher;
        $this->student = $student;
        $this->public = $public;
        $this->requestDate = date('Y-m-d H:i:s');
        $this->returnDate = date('Y-m-d H:i:s');
    }
}

2 个答案:

答案 0 :(得分:0)

我不确定为什么在同一请求中需要全部三个阅读器,因为在给定的事务中将只涉及其中的一个。如果您有这样的话:

abstract class Reader {}
class Teacher extends Reader {}
class Student extends Reader {}
class GeneralPublic extends Reader {}

...那么您的构造函数只需要一个参数,即基类:

public function __construct(Book $bookRequested, Reader $reader) {}

要配置内容,您只需创建一个属性或方法即可。如果您选择一种方法,那么您也可以获得使它抽象的优点:

abstract class Reader
{ 
    abstract public function getMaxBooks();
}

class Teacher extends Reader
{
    public function getMaxBooks() {
        return 10;
    }
}

答案 1 :(得分:0)

希望我能提供帮助,您可以在验证时检查类的类型。

class Reader{
    protected $requests;
    protected $name;
    public function get_name(){
        return $this->name;
    }
}
class Teacher extends Reader{

}
class Student extends Reader{

}
 class GeneralPublic extends Reader{

 }
 class Book{
     protected $name;
     public function __construct($name){
        $this->name = $name;
     }
 }
class Requests
{
    protected $bookRequested;
    protected $reader;
    protected $requestDate;
    protected $returnDate;

    public function __construct(Book $bookRequested, Reader $reader)
    {
        $this->bookRequested = $bookRequested;
        $this->reader = $reader;
        $this->requestDate = date('Y-m-d H:i:s');
        $this->returnDate = date('Y-m-d H:i:s');
    }
    public function validate(){
        echo get_class($this->reader);
    }
}
 $teacher = new Teacher();
 $student = new Student();
 $gen_pu = new GeneralPublic();

 $book = new Book("Travel");
 $req = new Requests($book,$teacher);
$req->validate();