php 调用方法前自动调用,如何在PHP中完成__constructor之后自动调用方法?

我写了一个名为Task的小型抽象类。我喜欢让每个任务逻辑的类来扩展它。如何在PHP中完成__constructor之后自动调用方法?

在我的抽象类“任务”中,我喜欢调用每个类中定义的已定义的“execute”方法。

我试图使用神奇的方法__call,但它不工作。

如果您在我的方法中注意到我回显消息,它永远不会在屏幕上打印。

这里是我的抽象任务类

namespace App\Modules\Surveys\Tasks;

use App\Modules\Surveys\Tasks\Support\Traits\HtmlHelper;

abstract class Task

{

/*

|

| This task base class provides a central location to place any logic that

| is shared across all of your tasks.

|

*/

use HtmlHelper;

/**

* checks wether a get method execute exists and calls it

*

* @param string $name

* @param array $args optional

* @return mixed

*/

public function __call($name, $args = [])

{

echo 'Attempt to execute task';

if (method_exists($this, 'execute')) {

return call_user_func_array('execute', $args);

} else {

throw new \Exception('execute method does does not exists in your task! ' . get_class($this));

}

}

}

?>

这是一个合乎逻辑的类

namespace App\Modules\Surveys\Tasks\Interviews;

use App\Modules\Surveys\Tasks\Task;

use App\Modules\Surveys\Models\SurveyInterview;

use Exception;

class ResumeInterview extends Task

{

protected $surveyId;

protected $callId;

protected $myInterview;

/**

* Create a new task instance.

*

* @return void

*/

public function __construct($surveyId, $callId)

{

$this->surveyId = intval($surveyId);

$this->callId = intval($callId);

}

/**

* Resume existing interview if one exists using the giving $surveyId and $callId

*

* @return void

*/

protected function execute()

{

//find the current interview if one exits

$myInterview = SurveyInterview::surveyAndCall($this->surveyId, $this->callId)->first();

$this->setInterview($myInterview);

if($this->wasResumed()){

//At this point existing interview was found

if($myInterview->status != 'Pending'){

//At this point the interview is completed and should not be conducted

throw new Exception('This interview can not not be retaken. It\'s current status is "' . $myInterview->status . '"');

}

}

}

/**

* Return the current interview

*

* @return App\Models\Survey\SurveyInterview

*/

public function getInterview()

{

return $this->myInterview;

}

/**

* It checks whether ot the the interview was resumed

*

* @return boolean

*/

public function wasResumed()

{

return $this->getInterview() ? true : false;

}

/**

* It sets the interview

*

* @param Illuminate\Support\Collection $myInterview

* @param void

*/

protected function setInterview($myInterview)

{

$this->myInterview = $myInterview;

}

}

我怎么会自动调用(如果存在)的执行方法,否则抛出异常?

2015-11-26

Mike A

+0

为什么不在你的父类构造函数中做这个,然后在子类中做'parent :: __ construct();'? –

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值