今天在引用阿里云SDK在Laravel下的应用时需要在每个类中添加命名空间,可恶的是没有alipay的Org包,开始没注意文件个数,人肉添加,越来越多…我发现这样并不是办法,并不是一两个文件,于是乎写了下面两个类适用于在单个或者多个文件中指定某行添加内容,根据以下两个类也可以做出更多需求的改变,也相信在更多的地方会使用到,看看实现吧,有建议欢迎提出。
在某个文件指定行的地方插入内容
类名:writeIntoFileContent.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| <?php
class writeIntoFileContent { private $file; private $code; private $lineNo; public function __construct($file, $code, $lineNo){ $this->file = $file; $this->code = $code; $this->lineNo = $lineNo; }
public function writeToLineContent() { $f = fopen($this->file, "r+"); $content = fread($f, filesize($this->file)); fclose($f); if (!strstr($content, $this->code)) { $arrInsert = $this->insertContent($this->file, $this->code, $this->lineNo-1); unlink($this->file); foreach ($arrInsert as $value) { file_put_contents($this->file, $value, FILE_APPEND); } } }
private function insertContent($file, $code, $lineNo) { $file_handle = fopen($file, "r"); $i = 0; $arr = array(); while (!feof($file_handle)) { $line = fgets($file_handle); ++$i; if ($i == $lineNo) { $arr[] = $line . $code . "\n"; } else { $arr[] = $line; } } fclose($file_handle); return $arr; }
}
|
在某个文件夹下所有的文件的指定行插入内容
类名:writeIntoAllFileContent.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| <?php
class writeIntoAllFileContent { private $filePath; private $code; private $lineNo; public function __construct($filePath, $code, $lineNo){ $this->filePath = $filePath; $this->code = $code; $this->lineNo = $lineNo; }
public function writeContentToAllFile() { $files = $this->findAllFile($this->filePath); if( !empty($files)){ foreach ($files as $fileName){ $file = $this->filePath.'/'.$fileName; $f = fopen($file, "r+"); $content = fread($f, filesize($file)); fclose($f); if (!strstr($content, $this->code)) { $arrInsert = $this->insertContent($file, $this->code, $this->lineNo-1); unlink($file); foreach ($arrInsert as $value) { file_put_contents($file, $value, FILE_APPEND); } } } }else{ echo "文件下面没有文件!"; exit; } }
private function insertContent($file, $code, $lineNo) { $file_handle = fopen($file, "r"); $i = 0; $arr = array(); while (!feof($file_handle)) { $line = fgets($file_handle); ++$i; if ($i == $lineNo) { $arr[] = $line . $code . "\n"; } else { $arr[] = $line; } } fclose($file_handle); return $arr; }
private function findAllFile($dir) { $files = array(); if(@$handle = opendir($dir)) { while(($file = readdir($handle)) !== false) { if($file != ".." && $file != ".") { if(is_dir($dir."/".$file)) { $files[$file] = $this->findAllFile($dir."/".$file); } else { $files[] = $file; } } } closedir($handle); return $files; } }
}
|