用文件写

问题描述 投票:0回答:1

我需要使用模板在CI中创建一个文件;创建的文件应该以<\ _?php string开头,所以我创建了一个如下模板:

<?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);

谢谢你的帮助

codeigniter file templates
1个回答
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转义\,因为$this无需扩展。

© www.soinside.com 2019 - 2024. All rights reserved.