我需要在CI中创建一个文件模板;创建的文件应该以< \?php字符串开头,所以我创建了一个类似下面的模板:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_<?php echo $class_name; ?> extends CI_Migration {
public function __construct()
{
parent::__construct();
}
public function up() {
$this->myforge->add_field(array(
'id' => array(
'type' => 'INT',
'constraint' => 11,
'auto_increment' => TRUE
)
));
$this->myforge->add_key('id', TRUE);
$this->myforge->create_table('<?php echo $table_name; ?>');
}
public function down() {
$this->myforge->drop_table('<?php echo $table_name; ?>');
}
}
Codeigniter控制器正确解析了$ class_name和$ table_name变量,但我无法正确写入第一行。
创建文件的控制器代码是:
$my_migration = fopen($path, "w") or die("Unable to create migration file!");
$templatedata['table_name'] = $table_name;
$templatedata['class_name'] = $class_name;
$migration_template = $this->load->view('adm/migration/templates/create_table_template.tpl.php',$templatedata,TRUE);
fwrite($my_migration, $migration_template);
fclose($my_migration);
感谢您的帮助
答案 0 :(得分:1)
将视图模板文件更改为以下内容可解决此问题。
<?php
echo
"<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_$class_name extends CI_Migration {
public function __construct()
{
parent::__construct();
}
public function up() {
\$this->myforge->add_field(array(
'id' => array(
'type' => 'INT',
'constraint' => 11,
'auto_increment' => TRUE
)
));
\$this->myforge->add_key('id', TRUE);
\$this->myforge->create_table('$table_name');
}
public function down() {
\$this->myforge->drop_table('$table_name');
}
}
";
我已将整个内容转换为字符串,删除了内容中的echo
语句,因为变量将通过php扩展,最后使用$this
转义\
以来{ {1}}无需扩展。