如何将一个大功能分为PHP中的小功能以获得最佳实践?
我创建了一个功能 exportFile ,将文件导出到.csv and .txt中的Amazon,Magento和来自数据库中的捕获量。既然,由于较长的标题以及一些重复的循环,该功能变得越来越大,如何将此功能分为单独的功能以获得最佳实践?
function exportFile ($fileName, $platform, $option) {
$test_db = new MysqliDb (TEST_DB_HOSTNAME, TEST_DB_USERNAME, TEST_DB_PASSWORD, TEST_DB_DATABASE);
$file = fopen(DOWNLOAD_FILE_PATH.$fileName, 'wb') OR die(json_encode(array("status" => "error", "errMessage" => "Error while downloading file!")));
if ($file) {
$query = "SELECT * FROM database";
$data = $test_db->rawQuery($query);
switch ($platform) {
case 'magento':
$header = array(
#csv titles goes here
);
fputcsv($file, $header);
foreach ($data as $rows) {
$csvData = array(
#csv records from database goes here
);
fputcsv($file, $csvData);
}
break;
case 'catch':
$header = array(
#csv titles goes here but not same as magento
);
fputcsv($file, $header);
foreach ($data as $rows) {
$csvData = array(
#csv records from database goes here but not same as magento
);
fputcsv($file, $csvData);
}
break;
}
}
}
I have created a function exportFile that export file into .csv and .txt for different platforms Amazon, Magento and catch from the database. Since, the function is getting big because of long headers as well as some repeated loops how can I divide this function into separate functions for best practices?
function exportFile ($fileName, $platform, $option) {
$test_db = new MysqliDb (TEST_DB_HOSTNAME, TEST_DB_USERNAME, TEST_DB_PASSWORD, TEST_DB_DATABASE);
$file = fopen(DOWNLOAD_FILE_PATH.$fileName, 'wb') OR die(json_encode(array("status" => "error", "errMessage" => "Error while downloading file!")));
if ($file) {
$query = "SELECT * FROM database";
$data = $test_db->rawQuery($query);
switch ($platform) {
case 'magento':
$header = array(
#csv titles goes here
);
fputcsv($file, $header);
foreach ($data as $rows) {
$csvData = array(
#csv records from database goes here
);
fputcsv($file, $csvData);
}
break;
case 'catch':
$header = array(
#csv titles goes here but not same as magento
);
fputcsv($file, $header);
foreach ($data as $rows) {
$csvData = array(
#csv records from database goes here but not same as magento
);
fputcsv($file, $csvData);
}
break;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有很多方法可以分解事物。这是一个起动器,
需要再迭代才能为CSVDATA创建功能。那是你要做的!
There are many ways to break things up. Here's a starter
One more iteration is required to make a function for csvData. That's for you to do !