0

我有以下模型,我在其中覆盖了的构造函数base class

class Tasks extends BaseTasks {    

    public function __construct($currentUser, $taskId, $startTime) {
        parent::__construct();
        //........
        //set all parameters to their respective fields
        //........
    }

当我使用手动创建任务时:$task= new Task('test_user',1,'10:15');一切正常。

问题是当我从数据库中获取所有任务时:

 $tasks = TasksQuery::create()->find();

我得到错误:

Warning: Missing argument 1 for Tasks::__construct(), called in...
Warning: Missing argument 2 for Tasks::__construct(), called in...
Warning: Missing argument 3 for Tasks::__construct(), called in...

堆栈跟踪显示 Propel 在调用构造函数然后 populateObject 以返回带有数据的任务对象:

Call Stack:
    //...other function calls
    0.1254   19326792  14. call_user_func(array (0 => 'TasksPeer', 1 => 'populateObject'), array (0 => '98', 1 => '2013-07-16 15:25:00', 2 => 'daily',...other params...) /library/propel1_6/formatter/PropelObjectFormatter.php:87
    0.1254   19326824  15. BaseTasksPeer::populateObject($row = array (0 => '98', 1 => '2013-07-16 15:25:00', ...other params...) /library/propel1_6/formatter/PropelObjectFormatter.php:87
    0.1254   19330456  16. Tasks->__construct($currentUser = ???, $taskId = ???, $startTime = ???) /models/om/BaseTasksPeer.php:485

现在,如果我决定在构造函数中使用值对象而不是原始数据类型,例如:

类任务扩展 BaseTasks {

    public function __construct(User $currentUser, $taskId, StartTime $startTime) {
        parent::__construct();
        //........
        //set all parameters to their respective fields
        //........
    }

对构造函数的调用将失败并出现致命错误!!有没有办法解决这个问题?

4

2 回答 2

0

Base 类调用构造函数,但没有参数。为了避免警告,使参数可选

public function __construct($currentUser = null, $taskId = null, $startTime = null) {
    ... 
}

当然,您可以根据应用程序的需要使用适当的值来代替 null。

于 2013-07-22T07:12:06.100 回答
0

简短的回答:没有明确的解决方案(构造函数 DI)。

我最终使用了 setter DI,在需要时调用 setter,第一次从控制器调用,然后在我需要的任何地方调用。但是随后您的控制器代码将受到 setter 调用的困扰……无论如何,我将向您展示:

//actions.class.php
...
$current_user = $this->getUser();
$item = ItemQuery::findPk($id);             // you can't override every find* method...
$item
  ->setUser($current_user);                 // setter DI here
  ->archiveIn($current_user->getOfficeId()) // custom method, see below
  ->save();
...

//Item.php
//you need to define getUser() and setUser() methods in this class
...
public function archiveIn($office_id) {
  $this
    ->setOfficeId($office_id)
    ->setArchivedBy($this->getUser()->getUsername());  // get the injected user
  return $this;                                        // keep method chainability
}
...
于 2013-08-02T15:30:59.470 回答