search
HomeBackend DevelopmentPHP Tutorial【求点评】生成缓存的一段代码,大家觉得有什么不足之处?代码风格方面

写了一段生成缓存的函数,大家觉得有什么不足之处?
代码的写的方式和风格方面,求评价

//cacheidfunction MakeThreeCache($ID){  $idArr = array(  'DIQU'    =>  array('id', 'name', '/cacheDiqu',   3,1,'中国','/1.php',"SELECT * FROM gk_common_diqu WHERE `level`=%d AND upid='%d' "),  'INFOCAT' =>  array('id', 'name', '/cacheInfocat',3,0,'大分类','/0.php',"SELECT * FROM gk_info_cat WHERE `level`=%d AND `able`=1 AND upid='%d' "),  );  if(!array_key_exists($ID,$idArr)) return false;  list($fnid,$fnvalue,$cacheDir,$deep,$upid1,$pos1,$firstFile,$selectSQL) = $idArr[$ID];  global $dsql;  set_time_limit(0);  $tm1 = microtime(true);  $dir1 = DEDEDATA.$cacheDir;  RmRecurse($dir1);//delete this dir first!  if(!is_dir($dir1) && !mkdir($dir1,0777)) exit('--|目录创建失败!'.$dir1 );  $path1 = $dir1.$firstFile;  $data1 = '<'."?php\n";  $data1.= "\n/* CACHE: {$ID} : {$pos1}\t */";  $data1.= "\n/* time:  ".date("Y-m-d H:i:s")." */";  $data1.= "\n/* path:  ".$path1." */\n";  $data1.= "\n\$CACHE['".$ID."'] = array(";  $dsql->Execute('s1',sprintf($selectSQL,1,$upid1));  while($row1 = $dsql->GetArray('s1'))  {    $data1 .= "\n".$row1[$fnid]."\t=>\t'".$row1[$fnvalue]."',";    $tm2 = microtime(true);    $pos2 = $pos1.' -> ['.$row1[$fnid].']'.$row1[$fnvalue];    $dir2 = $dir1."/".$row1[$fnid];    if(!is_dir($dir2) && !mkdir($dir2,0777))    {      echo("\n--|--|目录创建失败!".$dir2);      continue;    }    $path2 = sprintf('%s/%d.php',$dir2,$row1[$fnid]);    $data2 = '<'."?php\n";    $data2.= "\n/* CACHE: {$ID} : {$pos2}\t */";    $data2.= "\n/* time:  ".date("Y-m-d H:i:s")." */";    $data2.= "\n/* path:  ".$path2." */\n";    $data2.= "\n\$CACHE['".$ID."']['".$row1[$fnid]."'] = array(";    $dsql->Execute('s2',sprintf($selectSQL,2,$row1[$fnid]));    while($row2 = $dsql->GetArray('s2'))    {      $data2 .= "\n".$row2[$fnid]."\t=>\t'".$row2[$fnvalue]."',";      $tm3 = microtime(true);      $pos3 = $pos2.' -> ['.$row2[$fnid].']'.$row2[$fnvalue];      $dir3 = $dir2."/".$row2[$fnid];      if(!is_dir($dir3) && !mkdir($dir3,0777))      {        echo("\n--|--|--|目录创建失败!".$dir3);        continue;      }      $path3 = sprintf('%s/%d.php',$dir3,$row2[$fnid]);      $data3 = '<'."?php\n";      $data3.= "\n/* CACHE: {$ID} : {$pos3}\t */";      $data3.= "\n/* time:  ".date("Y-m-d H:i:s")." */";      $data3.= "\n/* path:  ".$path3." */\n";      $data3.= "\n\$CACHE['".$ID."']['".$row1[$fnid]."']['".$row2[$fnid]."'] = array(";      $dsql->Execute('s3',sprintf($selectSQL,3,$row2[$fnid]));      while($row3 = $dsql->GetArray('s3'))      {        $data3 .= "\n".$row3[$fnid]."\t=>\t'".$row3[$fnvalue]."',";      }      $data3.= "\n);\n\n/* [level=3]all taken ".sprintf('%.6f',microtime(true)-$tm3)."s  */\n?".'>';      $fp3 = fopen($path3,'w');      fwrite($fp3,$data3);      fclose($fp3);    }    $data2.= "\n);\n\n/* [level=2]all taken ".sprintf('%.6f',microtime(true)-$tm2)."s  */\n?".'>';    $fp2 = fopen($path2,'w');    fwrite($fp2,$data2);    fclose($fp2);  }  $data1.= "\n);\n\n/* [level=1]all taken ".sprintf('%.6f',microtime(true)-$tm1)."s  */\n?".'>';  $fp1 = fopen($path1,'w');  fwrite($fp1,$data1);  fclose($fp1);  return true;}



生成的内容1:(表diqu)
<?php/* CACHE: DIQU : 中国 -> [6]广东 -> [76]广州	 *//* time:  2012-12-21 12:28:42 *//* path:  D:/website/35***.com/www/data/cacheDiqu/6/76/76.php */$CACHE['DIQU']['6']['76'] = array(692	=>	'从化市',693	=>	'天河区',694	=>	'东山区',695	=>	'白云区',696	=>	'海珠区',697	=>	'荔湾区',698	=>	'越秀区',699	=>	'黄埔区',700	=>	'番禺区',701	=>	'花都区',702	=>	'增城区',703	=>	'从化区',704	=>	'市郊',);/* [level=3]all taken 0.002312s  */?>


生成的内容2:(表infocat)
<?php/* CACHE: INFOCAT : 大分类	 *//* time:  2012-12-21 12:28:43 *//* path:  D:/website/***.com/www/data/cacheInfocat/0.php */$CACHE['INFOCAT'] = array(10001	=>	'照明工业',10152	=>	'电子元器件',10272	=>	'传媒、广电',10392	=>	'安全、防护',10603	=>	'包装',10788	=>	'纸业',10897	=>	'办公、文教',11183	=>	'数码、电脑',11384	=>	'电工电气',11694	=>	'纺织、皮革',11894	=>	'服装',12015	=>	'服饰',12069	=>	'机械及行业设备',13100	=>	'五金、工具',13506	=>	'化工',14224	=>	'精细化学品',14643	=>	'橡塑',14932	=>	'环保',15128	=>	'仪器仪表',15520	=>	'家居用品',15805	=>	'家用电器',15967	=>	'建筑、建材',16437	=>	'交通运输',16597	=>	'礼品、工艺品、饰品',16838	=>	'能源',16978	=>	'农业',17300	=>	'汽摩及配件',17636	=>	'食品、饮料',17906	=>	'通信产品',18034	=>	'玩具',18092	=>	'冶金矿产',18536	=>	'印刷',18712	=>	'运动、休闲',18940	=>	'商务服务',19177	=>	'项目合作',19233	=>	'二手设备转让',19278	=>	'加工',19455	=>	'代理',19512	=>	'库存积压',);/* [level=1]all taken 5.697496s  */?>







回复讨论(解决方案)

//检测是否正确的代码:

//检测三级数据,DIQU,INFOCAT/*1) deep=1,d1=0,d2>0,d3>0          d1=0,d2=0,d3=0          d1>0,d2>0,d3=0          d1>0,d2=0,d3=0          d1>0,d2>0,d3>02) deep=2,d1>0,d2>0,d3>03) deep=3,d1>0,d2>0,d3>0*/function CheckThree($cacheID='DIQU',$dataArray=array(),$deep=2){  if(empty($dataArray)) return array(false,'缺少传入的数值参数'); //缺少传入的参数  $cacheArr = array(  'DIQU'  =>  array('DIQU','/cacheDiqu','/1.php','MakeDiquCache','地区'),  'INFOCAT' =>  array('DIQU','/cacheInfocat','/0.php','MakeInfocatCache','信息分类'),  );  if(!array_key_exists($cacheID,$cacheArr)) return array(false,'ID参数错误!');  list($varName,$cacheDirName,$firstFile,$cacheMakeFuncName,$cnName) = $cacheArr[$cacheID];  if(!is_dir(DEDEDATA.$cacheDirName)) $cacheMakeFuncName($cacheID);  list($d1,$d2,$d3) = $dataArray;  $returnData = array();  if($d1>0)  {    $path1 = DEDEDATA.$cacheDirName.$firstFile;    if(!file_exists($path1)) return array(false,'SysError-'.$cacheID.'-d1 file not found!');    include $path1;    if(!array_key_exists($d1,$CACHE[$cacheID])) return array(false,'您选择的['.$cnName.']一级属性错误!');    $returnData[] = $CACHE[$cacheID][$d1];    //防止情况[deep=1,d1>0,d2>0,d3=0],[deep=1,d1>0,d2=0,d3>0]    if($deep < 2 && !$d2 && !$d3) return array(true,$returnData);    if($d2>0)    {      $path2 = DEDEDATA.$cacheDirName."/{$d1}/{$d1}.php";      if(!file_exists($path2)) return array(false,'SysError-'.$cacheID.'-d2 file not found!');      include $path2;      if(!array_key_exists($d2,$CACHE[$cacheID][$d1])) return array(false,'你选择的['.$cnName.']二级属性错误!');      $returnData[] = $CACHE[$cacheID][$d1][$d2];      //防止情况 [deep=2,d1>0,d2>0,d3>0]导致d3不检查      if($deep<3 && !$d3) return array(true,$returnData);      if($d3>0)      {        $path3 = DEDEDATA.$cacheDirName."/{$d1}/{$d2}/{$d2}.php";        if(!file_exists($path3)) return array(false,'SysErro-'.$cacheID.'-d3 file not found!');        include $path3;        if(!array_key_exists($d3,$CACHE[$cacheID][$d1][$d2])) return array(false,'您选择的['.$cnName.']三级属性分类错误!');        $returnData[] = $CACHE[$cacheID][$d1][$d2][$d3];        return array(true,$returnData);      } else {        return array(false,'您没有选择['.$cnName.']的三级属性');      }    } else {      return array(false,'您没有选择['.$cnName.']的二级属性');    }  } else {    return array(false,'您没有选择['.$cnName.']的一级属性');  }  //默认也返回数据  return array(true,$returnData);}



求点评,代码风格和方式……

    while($row2 = $dsql->GetArray('s2'))
    {
      $data2 .= "\n".$row2[$fnid]."\t=>\t'".$row2[$fnvalue]."',";
 
      $tm3 = microtime(true);
      $pos3 = $pos2.' -> ['.$row2[$fnid].']'.$row2[$fnvalue];
      $dir3 = $dir2."/".$row2[$fnid];
      if(!is_dir($dir3) && !mkdir($dir3,0777))
      {
        echo("\n--|--|--|目录创建失败!".$dir3);
        continue;
      }
表示的是如果无法创建目录就跳过,是吧?
也就是可能什么都缓存不了了?是这个意思吧?

不错

1 array_key_exists很直观,但是不如isset效率高
2 能不用global

1 array_key_exists很直观,但是不如isset效率高
2 能不用global就别用
3 mkdir别777,你这个是缓存,600就够用了

while($row2 = $dsql->GetArray('s2'))
    {
      $data2 .= "\n".$row2[$fnid]."\t=>\t'".$row2[$fnvalue]."',";
 
      $tm3 = microtime(true);
      $pos3 = $pos2.' -> ['.$row2[$fn……

逻辑上是这样想的。因为不想一半就停止了。确实比较不太妥,不过有提示

自己的看法就是,现在看这一大段,感觉好臃肿,但是没有更简便的了。。哈哈哈~

自我点评:写的很乱~ ~ 不过貌似没有其他更好的办法了?

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.