0

I need to create a file in CI usgin a template; the file created should starts with <\?php string so I created a template like the following one:

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

}

The $class_name and $table_name variables are parsed correctly by the Codeigniter controller but I'm not able to write correctly the first row.

The controller code to create the file is:

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

Thanks for any help

1 Answer 1

1

Changing your view template file to the following should solve the issue.

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

}
";

I have converted the whole content to a string, removed the echo statements within the content since the variable will be expanded by php, and finally escaped $this using a \ since $this need not be expanded.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.