In this class, the teacher led us to create TEMPLATE. According to the teacher's teaching, we hope to write the code in this way: 1. For example, I define a variable $name=‘’; 2. Then I read a template. 3. Then I set some of my own "display formats" (hard style) in this template. 4. After loading the template, you can directly replace it with the above variables.
1. First create a new index.tpl in the template folder. The content is written like this
<?php echo '<?php' ?> /** * project name: <?php echo $prj_name ?> //大家想想, 它能运行吗? *User: <?php echo $prj_author ?> //能运行吗? *Date: <?php echo date('Y-m-d')?> //能吗? */ echo "hello shenyi"; ?>
Okay, the preparations are done, we reference it in the god_frame class:
<?php namespace core\frame; class god_frame { public $project_folder = ''; //项目文件夹 public $project_main = ''; //入口文件 function __construct($prjName){ //构造函数 $this->project_folder = getcwd()."/".$prjName; $this->project_main = $this -> project_folder."/index.php"; } function run(){ //判断并生成新的文件夹,没有就创建 !file_exists($this->project_folder) && mkdir($this->project_folder); //获取外部成员变量并把该函数获取的数组返回成变量列表 extract(get_object_vars($this)); 开启PHP的内部缓冲区(内存) ob_start(); //引入模板路径 include (dirname(__FILE__).'/template/index.tpl'); //获取缓冲区的内容,并赋给$cnt $cnt =ob_get_contents(); //清理缓冲区内容 ob_end_clean(); //在该文件夹下生成一个index.php文件,没有就创建并覆盖 file_put_contents($this->project_main,"$cnt"); } } ?>
I also need to improve the start (method) in godinit
static function start(){ $get_config = loadConfig(); $gf = new god_frame($get_config->prj_name); $gf -> prj_name = $get_config->prj_name; $gf -> prj_author = $get_config->prj_author; $gf -> run(); }
Execute this method in the command line
Then let’s take a look at the directory structure of the entire document and the contents of index.php
Added knowledge points:
__FILE__:
dirname():
ob_start(): Start PHP internal buffer (memory). Put the content to be displayed next into the buffer first, and display it without haste.
ob_get_contents(); function to get the contents of the buffer
ob_end_clean(); You can clear the buffer contents, so that Output content
ob_end_flush(); Close the buffer and output the content
get_object_vars(); You can get the attribute variable values in the class (the instantiated class) and return the array.
extract();