Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CodeSmith automatically generates a simple template for the Yii Framework ActiveRecord class


May 25, 2021 CodeSmith


Table of contents


Automatically generate simple templates for theIi Framework ActiveRecord class

The above example describes the basic method of writing code templates using CodeSmith, and in this case, implementing a more useful code template that automatically generates the required ActiveRecord class for Yii Framework through a database.

This example is an ActiveRecord by modifying the Yii Framework Development Tutorial (26) Database-Active Record .php manually.

First add a C# project to the project (any type, we'll just use this project to include the CodeSmith project), then add a CodeSmith project and a CodeSmith template. Then refer to CodeSmith Using Tutorial (1): Overview Use Schema Explorer to add a data connection, in this case to the Chinook database:

CodeSmith automatically generates a simple template for the Yii Framework ActiveRecord class

The code template created by PhpActiveRecord.cst defines a property TableName (database table name), copies the definition of Employee.php in the Yii Framework Development Tutorial (26) Database-Active Record example, and uses the following code:

<%@ Template Language="C#" TargetLanguage="PHP" Debug="False" %>

<%@ Property Name="TableName" Type="System.String" Description="Table name" %>

<?php

class <%= TableName %> extends CActiveRecord
{
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    public function tableName()
    {
        return '<%= TableName %>';
    }
}

?>

<script runat="template">
  public override string GetFileName() {
    return TableName + ".php" ;
}
</script>

You can then generate the corresponding ActiveRecord PHP class for any data table by defining tableName's properties. B ut it's still up to you to manually configure the table names one by one. This example automatically generates the corresponding ActiveRecord for all tables by connecting to the database through a master template and a way from the template

Using the specific usage of the main template later introduced, simply said sub-template is equivalent to a sub-function, the main template is similar to the main function can call sub-functions, the main template by calling sub-templates, passed to sub-template properties so that you can generate multiple files.

Create a code template YiiDataModel.cst as the main template, and use the sub-template to register in the main template before you can use it:

<%@ Register Name="ActiveRecord" Template="PhpActiveRecord.cst" MergeProperties="false"  %>

The full code is as follows:

<%@ CodeTemplate Language="C#" TargetLanguage="Text"
  Description="List all database tables" %>
<%@ Import Namespace="System.IO" %>
<%@ Property Name="SourceDatabase" Type="SchemaExplorer.DatabaseSchema"
  Category="Context" Description="Database containing the tables." %>

<%@ Register Name="ActiveRecord" Template="PhpActiveRecord.cst"
 MergeProperties="false"  %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>

<script runat="template">
public string FirstLetterToUpper(string str)
{
    if (str != null)
    {
        if(str.Length > 1)
            return char.ToUpper(str[0]) + str.Substring(1);
        else
            return str.ToUpper();
    }
    return str;
}

</script>

<% for (int i = 0; i < SourceDatabase.Tables.Count; i++) { %>
   <%  string name= FirstLetterToUpper(SourceDatabase.Tables[i].Name); %>
   <%  string filename= @"../ActiveRecordDemo/protected/models/"+name+".php"; %>
     // instantiate the sub-template
    <%  ActiveRecord activeRecord = this.Create<ActiveRecord>();%>
    <%  activeRecord.TableName= name; %>
    <%  activeRecord.RenderToFile(filename,true); %>
<% } %>

FirstLetterToUpper is a function of C, which mainly changes the first letter of the database table name to capital (pure C# code).

SchemaExplorer provides CodeSmith with a database access library that can be used to obtain information about the database Schema, such as the table name contained, field properties, primary key foreign keys, etc. (detailed later)

In the main template, the sub-template is accessed through ActiveRecord (the name ActiveRecord is defined when the sub-template was registered), the sub-template instance is created using this.create, and then passed into the TableName property, calling RenderToFile to write the results of the sub-template to the specified file.

At this point, add the main template to CodeSmith.csp, configure the database as Chinook, and generate code

Rendering output 'YiiDataModel'...

  Generated: D:\tmp\ActiveRecordDemo\ActiveRecordDemo\protected\models\Album.php
  Generated: D:\tmp\ActiveRecordDemo\ActiveRecordDemo\protected\models\Artist.php
  Generated: D:\tmp\ActiveRecordDemo\ActiveRecordDemo\protected\models\Customer.php
  Generated: D:\tmp\ActiveRecordDemo\ActiveRecordDemo\protected\models\Employee.php
  Generated: D:\tmp\ActiveRecordDemo\ActiveRecordDemo\protected\models\Genre.php
  Generated: D:\tmp\ActiveRecordDemo\ActiveRecordDemo\protected\models\Invoice.php
  Generated: D:\tmp\ActiveRecordDemo\ActiveRecordDemo\protected\models\Invoiceline.php
  Generated: D:\tmp\ActiveRecordDemo\ActiveRecordDemo\protected\models\Mediatype.php
  Generated: D:\tmp\ActiveRecordDemo\ActiveRecordDemo\protected\models\Playlist.php
  Generated: D:\tmp\ActiveRecordDemo\ActiveRecordDemo\protected\models\Playlisttrack.php
  Generated: D:\tmp\ActiveRecordDemo\ActiveRecordDemo\protected\models\Track.php
  Generated: D:\tmp\ActiveRecordDemo\CodeSmith\YiiDataModel.txt
Done rendering outputs: 1 succeeded, 0 failed, 0 skipped (1

The refresh project can see the automatically generated code file

CodeSmith automatically generates a simple template for the Yii Framework ActiveRecord class

This example is simply generating the simplest ActiveRecord for each data table, and if you need to generate an associated ActiveRecord, you can further generate the desired relations method for each ActiveRecord based on the relationships between the tables, which will be covered later.

This example Downloads