基本上我想让一个课程说'工作',大致是这样的。
class Job {
$jobId;
$name;
public function __construct($name) {
$this->name = $name;
}
public function execute() {
// excute some stuff here
}
public function setJobId() {
$this->jobId = $this->generateId();
}
public function view() {
return $this->name;
}
// Other stuffs
}
要求是:
客户端应该可以实例化这个类,他们可以执行$ job = new Job()并执行$ job-> view()来获取作业名称。但是,如果客户端想要执行它,则需要设置ID。请注意,此ID只应设置一次。此外,客户端可能只想检索作业名称而不想执行它。
洞察?也许我不应该让客户端实例化该类只是为了得到它的名字?
答案 0 :(得分:1)
我会考虑以下选项:
删除setJobId()
并在构造函数中分配作业标识符:
...
public function __construct($name) {
$this->name = $name;
$this->jobId = $this->generateId();
}
...
删除setJobId()
并在执行中分配作业标识符
...
public function execute() {
$this->jobId = $this->generateId();
// execute some stuff here
}
...
请确保setJobId()
不会重新分配ID,但我可能会将其重命名为prepare()
更直观的内容:
...
public function prepare() {
if (is_null($this->jobId)) { // or however nullity is checked on PHP
$this->jobId = $this->generateId();
} else {
// do nothing or raise exception
// because I've just found out that PHP has exceptions
}
}
...
如果您不执行1.或2.之类的操作,则可以在jobId
内查看execute()
,如果尚未设置,则引发错误或致电{{ 1}} - 或者他性感的新版本setJobId()
; ^)