[英]PHP - OOP return objects or array?
I'm just starting to learn OOP as my usual procedural approach is beginning to become messy when dealing with larger projects. 我刚开始学习OOP,因为在处理较大的项目时,我通常的程序方法开始变得混乱。 I've ran into a few things i'm unsure about early on.
我碰到了一些我不确定的事情。
The idea is simply adding new members to a database, and pulling a list of existing members from the database. 这个想法只是将新成员添加到数据库,然后从数据库中提取现有成员的列表。
I've put some comments in my code as well as the questions below. 我在代码中以及以下问题中添加了一些注释。
class memberManager
{
public $members;
public function createMember($db, $array) // Should I pass in an array or seperate items?
{
// Db code
}
public function getAllMembers($db)
{
// Should I return an array, then loop through in my script creating the "member" objects, or should I create and return them directly in this function?
$dbconnection = $db->prepare("SELECT * FROM members");
$dbconnection->execute();
$x = 0;
while ($row = $dbconnection->fetch())
{
$members[$x]['firstname'] = $row['firstname'];
$members[$x]['lastname'] = $row['lastname'];
$members[$x]['dob'] = $row['dob'];
$x++;
}
return $members;
}
}
class member
{
public $firstname, $lastname, $dob;
function __construct($details)
{
$this->firstname = $details['firstname'];
$this->lastname = $details['lastname'];
$this->dob = $details['dob'];
}
}
members-list.php 会员制list.php的
$memberManager = new memberManager();
$membersList = $memberManager->getAllMembers($db);
foreach ($membersList as $existingMember)
{
$member = new member($existingMember);
}
Hopefully this makes sense, It's written in a bit of a pseudocode-ish manner just to highlight the problems. 希望这是有道理的,只是为了突出问题而以一种伪代码的方式编写。
I will pass an array. 我将传递一个数组。 As you said, it is easier to add a new property.
如您所说,添加新属性更加容易。
I will return an array of objects and I will have a member entity that it will make easier to work with the properties. 我将返回一个对象数组,并且我将拥有一个成员实体,这将使使用属性更加容易。 My answer is just a personal opinion.
我的回答只是个人意见。
Note: this question can have multiple different answers, since, it will depends on the developer preferences 注意:这个问题可以有多个不同的答案,因为这将取决于开发人员的偏好
I know I am not exactly answering your question, but for basic CRUD I would really recommend some ORM framework. 我知道我并没有完全回答您的问题,但是对于基本的CRUD,我真的会推荐一些ORM框架。
As for your question, I think using separate entity classes over arrays is way to go - you sacrifice flexibility but in return you can keep entity specific logic in one place, which goes well with DRY principle . 关于您的问题,我认为在数组上使用单独的实体类是一种方法-您牺牲了灵活性,但作为回报,您可以将实体特定的逻辑放在一个地方,这与DRY原理非常吻合。
Please also note that your class naming is slightly off. 另请注意,您的班级命名略有不同。 While PHP does not definitive any naming conventions, for class names PascalCase is mostly used.
尽管PHP并没有明确的任何命名约定,但对于类名, PascalCase却被广泛使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.