PHP写PHP文件

                                                                               PHP写PHP文件

1、效果

2、代码

/**
 * @todo 调用方法
 */
public function testAction(){
	$id = isset($_GET['id']) ? (int)$_GET['id'] : '';
	if (empty($id)){
		die('参数缺失');
	}
	$this->createNewPage($id);
	exit();
}

/**
 * @todo 根据ID往类中写不同的方法
 * @param unknown $id
 */
function createNewPage($id){
	/** 添加控制器 */
	$filePath = APP_PATH.'/app/controllers/Test.php';
	if(!file_exists($filePath)){
		$content = '<?php'.PHP_EOL.
		'class AboutController extends BasicController {'.PHP_EOL.
		'	public function getPage($id){'.PHP_EOL.
		'		$mTest = new TestModel();'.PHP_EOL.
		'		$info = $mTest->getOne([["id",$id]]);'.PHP_EOL.
		'		$this->getView()->assign("info", $info);'.PHP_EOL.
		'		$this->display("index");'.PHP_EOL.
		'		exit();'.PHP_EOL.
		'	}'.PHP_EOL.
		'}';
		file_put_contents($filePath, $content, FILE_APPEND | LOCK_EX );
	}

	/** 添加类 */
	$actionName = 'test'.$id.'Action';
	$actionContent = 	'	public function '.$actionName.'(){'.PHP_EOL.
	'		$this->getPage('.(int)$id.');'.PHP_EOL.
	'	}'.PHP_EOL.
	'}';

	/** 把类追加到之前的文件中 */
	$count = count(file($filePath));
	$fp = fopen( $filePath, 'r+' );
	if ($fp) {	//修改最后一行的数据
		$i = 1;
		while (!feof($fp)) {
			if ($i == $count) {	//修改最后一行数据
				fseek($fp, 0, SEEK_CUR);	//替换某一行
				fwrite($fp, $actionContent);			//替换某一行的详情
				break;
			}
			fgets($fp);
			$i++;
		}
		fclose($fp);
	}
}

3、由于Test.PHP文件中的方法都是相似的,所以不需要每次创建的时候都给文件追加一个方法;直接写一个公共的方法就好啦。

修改如下:

public function noticeAction(){
    $this->getPage($_GET['id']);
}

猜你喜欢

转载自blog.csdn.net/qq_36025814/article/details/82957458
php