放置一个方法 class

Place a method in which class

我有一个问题更像是最佳实践,而不是实际问题。

假设我正在构建一个项目应用程序,每个项目都有多个任务需要完成。

所以项目 class:

class Project {
    public $id;
    public $name;

    // Get tasks of this project
    public function getTasks() {
            // some logic to get tasks of this project
    }

    // Should a method for adding task go here
    public function addTask() {
           // some logic going here
    }
}

以及任务class:

class Task {
     public $id;
     public $name;

     // Should a method for adding task go here
     public function add_task($project_id) {
          // The task class here needs to know the project_id
          // to continue with the logic
     }
}

如您所知,任何任务总是属于某个项目。

添加任务应被视为任务的一种方法,或者因为任何任务始终属于项目,所以它应该是项目的一部分 class??有更正确的吗?所以一个task就是一个task同时又属于一个project

单一职责原则

A class should have one and only one reason to change, meaning that a class should have only one job.

如果 Project class 的职责是管理任务,addTask 应该是一个 Project 方法。

考虑将 addTask 方法添加到任务的可能性。这将违反任务的单一职责 class。然后 Task 将代表一个任务,plus 然后它将负责将自己添加到某个任务集合中。

面向对象的编程允许我们保留许多 类 来满足更具体的对象,并最终允许我们保证应用程序中的某些结构或行为。

考虑到这一点,您应该记住您的对象可以使用带有可选参数的构造函数创建。这意味着我们可以创建我们的项目和任务,并且知道它们遵守特定条件。

请考虑以下代码:

class Project {
    public $id = 0;
    public $name = '';
    public $tasks = [];

    // Creates a new class, project, with the specified parameters.
    __construct($i = 0, $n = "", $t = []) {
      $id = $i;
      $name = $n;
      $tasks = $t;
    }

    // Get tasks of this project
    public function getTasks() {
            return $tasks;
    }

    // A function to create a new task and assign it to our tracked list of takss
    public function addTask($i, $n) {
           array_push($tasks, new Task($i, $n);
    }
}


class Task {
     public $id;
     public $name;

     // Creates a new class, tasks, with the specified parameters.
    __construct($i = 0, $n = "") {
      $id = $i;
      $name = $n;
    }
}

然后,在页面的其他地方或应用程序的一部分,您可以简单地调用。

$project = new Project(1, "The First Project", []);
$project.addTask(1, "My first task");
$project.addTask(2, "My second task");
var_dump($project.getTasks());
// You will see an array of your two tasks.