我有一个CSV类,可以读取和写入CSV文件。 我有一个模型类User,我想要一个方法,该方法通过ID(getUserById)从CSV返回我一个User对象; 因此,CSV应该返回User类对象。 问题是我希望CSV从Book对象调用时也返回Book对象。
我阅读了有关DI和反射的信息,但我不明白如何使用它。
import accounts from '../models/account/'
class Transaction {
static debitAccount(req, res) {
let m = moment();
const created_on = m.format('dddd, MMMM Do YYYY, h:mm a');
const {
amount,
old_balance,
transaction_type,
cashier
} = req.body;
let x, y, sum;
x = amount
y = old_balance;
sum = parseFloat(x) + parseFloat(y);
accounts.forEach((account) => {
const account_id = account.account_number;
});
const newDebit = {
created_on: created_on,
transaction_id: transactions.length + 1,
account_number: account_id,
cashier: parseInt(cashier),
transaction_type: transaction_type,
old_balance: parseFloat(old_balance),
amount: parseFloat(amount),
new_balance: sum
}
console.log('New Debit', newDebit);
transactions.push(newDebit);
res.status(201).send({
status: 201,
message: 'Amount successfully debited!',
data: newDebit
})
}
class User
{
private $firstname;
private $lastname;
private $username;
private $password;
public function __construct($firstname, $lastname, $username, $password)
{
$this->firstname = $firstname;
$this->lastname = $lastname;
$this->username = $username;
$this->password = $password;
}
public static function getUsers()
{
require_once 'CSV.php';
$csv=new CSV('r',USERS);
$CSVusers= $csv->getAll();
$users=array();
foreach ($CSVusers as $CSVuser){
$users[]=new User($CSVuser[0],$CSVuser[1],$CSVuser[2],$CSVuser[3],$CSVuser[4],$CSVuser[5],$CSVuser[6]);
}
return $users;
}
public static function getUserByUsername($username )
{
require_once 'CSV.php';
$csv=new CSV('r',USERS);
$CSVusers= $csv->getAll();
$users=array();
foreach ($CSVusers as $CSVuser){
$users[]=new User($CSVuser[0],$CSVuser[1],$CSVuser[2],$CSVuser[3]);
}
foreach ($users as $user){
if($user->getUsername()==$username){
return $user;
}
}
}
}
此刻,我从CSV文件获取了一个数组,并将其转换为模型中的对象,但我认为这不是最佳解决方案。