{"id":124,"date":"2011-11-09T13:06:21","date_gmt":"2011-11-09T05:06:21","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=124"},"modified":"2018-09-03T21:16:10","modified_gmt":"2018-09-03T13:16:10","slug":"generate-php-codes-with-php","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/generate-php-codes-with-php\/","title":{"rendered":"Generate PHP codes with PHP"},"content":{"rendered":"<p>Throughout my programming years, I observed similar trends in code structures and I felt that being able to generate them automatically will greatly reduce development time. <\/p>\n<p>Although there are many code generation software on the web, coding one for your own usage can be simpler and more convenient, especially when you had written custom functions that your generated codes will utilize. <\/p>\n<p>In this post, I shall discuss my recent experience in creating a PHP code generator for my own usage. <\/p>\n<h3>A simple case study<\/h3>\n<p>Suppose that given a class name and a comma-delimited string of variable names:<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;?php\r\n$classname = 'Person';\r\n$variables = 'age, name';\r\n?&gt;\r\n<\/pre>\n<p>We want to generate a POJO equivalence in PHP automatically, which resembles the following form:<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;?php\r\nclass Person {\r\n\r\n    private $name;\r\n    private $age;\r\n\r\n    public function getName() {\r\n        return $this-&gt;name;\r\n    } \/\/ end public function getName()\r\n\r\n    public function setName($name) {\r\n        $this-&gt;name = $name;\r\n    } \/\/ end public function setName($name)\r\n\r\n    public function getAge() {\r\n        return $this-&gt;age;\r\n    } \/\/ end public function getAge()\r\n\r\n    public function setAge($age) {\r\n        $this-&gt;age = $age;\r\n    } \/\/ end public function setAge($age)\r\n} \/\/ end class Person\r\n\r\n?&gt;<\/pre>\n<h3>Perform the necessary work<\/h3>\n<h4>Capitalise the first character of the variable name<\/h4>\n<p>To capitalise the first character of the variable name to form the getXXX and setXXX methods, we can use the <code>ucfirst<\/code> function.<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;?php\r\n\/\/ Form the method name of the getter method \r\n$getterMethodName = 'get' . ucfirst('age');\r\n?&gt;\r\n<\/pre>\n<h4>Get the end of line<\/h4>\n<p>The end of line is represented differently in different operating systems. Use the php constant <strong><code>PHP_EOL<\/code><\/strong> instead of <strong>\\r<\/strong> or <strong>\\n<\/strong> to output the end of line in a cross platform manner.<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;?php\r\n\/\/ Variable contains the end of line character(s).\r\n$endOfLine = PHP_EOL;\r\n?&gt;\r\n<\/pre>\n<h4>Get the tab character<\/h4>\n<p>The tab character is represented with the <strong>\\t<\/strong> literal. To output the tab character, enclose it with double quotes instead of single quotes. Using single quotes will display two characters <strong>\\<\/strong> and <strong>t<\/strong> instead of the tab character.<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;?php\r\n\/\/ Variable contains the tab character\r\n$tab = &quot;\\t&quot;;\r\n\/\/ Variable contains the \\ and t characters\r\n$slashAndT = '\\t';\r\n?&gt;\r\n<\/pre>\n<h4>Write the codes to file<\/h4>\n<p>To write the codes to file, we can use the <code>fopen<\/code> and <code>fwrite<\/code> functions.<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;?php\r\n\/\/ Save the generated file to a sibling folder of the running script\r\n$generatedFileUrl  = dirname($_SERVER&#x5B;'SCRIPT_FILENAME']);\r\n$generatedFileUrl .= '\/generated-codes\/' . $className . '.inc.php';\r\n$fp = fopen($generatedFileUrl, 'w+');\r\n    \r\n\/\/ Write the start script tag\r\nfwrite($fp, '&lt;?php' . PHP_EOL);\r\n?&gt;\r\n<\/pre>\n<h3>A sample (Plain Old PHP Object) POPO code generation script<\/h3>\n<p>The following is a sample script that I wrote for generating POPOs using the above-mentioned PHP features. Since this is a script to help developers, I did not include error handling to filter invalid class names or variable names. If you use it the right way, it can be helpful to you. \ud83d\ude42<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;?php\r\n\r\n$className = '';\r\n$variableNames = '';\r\n\r\nif (isset($_POST&#x5B;'text_class_name']) &amp;&amp; isset($_POST&#x5B;'text_variable_names'])) {\r\n    \r\n    $className = trim($_POST&#x5B;'text_class_name']);\r\n    $variableNames = str_replace(' ', '', trim($_POST&#x5B;'text_variable_names']));\r\n\r\n    $variableNamesArray = explode(',', $variableNames);\r\n    \r\n    \/\/ Save the generated file to a sibling folder of the running script\r\n    $generatedFileUrl  = dirname($_SERVER&#x5B;'SCRIPT_FILENAME']);\r\n    $generatedFileUrl .= '\/generated-codes\/' . $className . '.inc.php';\r\n    $fp = fopen($generatedFileUrl, 'w+');\r\n    \r\n    \/\/ Write the start script tag\r\n    fwrite($fp, '&lt;?php' . PHP_EOL);\r\n    \r\n    fwrite($fp, 'class ' . $className . ' {' . PHP_EOL . PHP_EOL);\r\n    \r\n    \/\/ Output the instance variables\r\n    foreach($variableNamesArray as $variableName) {\r\n        fwrite($fp, &quot;\\t&quot; . 'private $' . $variableName . ';' . PHP_EOL);\r\n    }\r\n    \r\n    fwrite($fp, PHP_EOL);\r\n    \r\n    \/\/ Output the getter and setter methods\r\n    foreach ($variableNamesArray as $variableName) {\r\n        \r\n        $ucVariableName = ucfirst($variableName);\r\n        \r\n        \/\/ getter \r\n        fwrite($fp, &quot;\\tpublic function get&quot; . $ucVariableName . '() {' . PHP_EOL);\r\n        fwrite($fp, &quot;\\t\\t&quot; . 'return $this-&gt;' . $variableName . ';' . PHP_EOL );\r\n        fwrite($fp, &quot;\\t} \/\/ end function get&quot; . $ucVariableName . '()' . PHP_EOL . PHP_EOL);\r\n        \r\n        \/\/ setter \r\n        fwrite($fp, &quot;\\tpublic function set&quot; . $ucVariableName . '($' . $variableName . ') {' . PHP_EOL);\r\n        fwrite($fp, &quot;\\t\\t&quot; . '$this-&gt;' . $variableName . ' = $' . $variableName . ';' .  PHP_EOL);\r\n        fwrite($fp, &quot;\\t} \/\/ end function set&quot; . $ucVariableName . '($' . $variableName . ')' . PHP_EOL . PHP_EOL);\r\n        \r\n    } \/\/ end foreach\r\n    \r\n    fwrite($fp, '} \/\/ end class ' . $className . PHP_EOL);\r\n    fwrite($fp, '?&gt;');\r\n    \r\n} \/\/ end if\r\n\r\n?&gt;\r\n&lt;!DOCTYPE html PUBLIC &quot;-\/\/W3C\/\/DTD XHTML 1.0 Strict\/\/EN&quot; &quot;http:\/\/www.w3.org\/TR\/xhtml1\/DTD\/xhtml1-strict.dtd&quot;&gt;\r\n&lt;html xmlns=&quot;http:\/\/www.w3.org\/1999\/xhtml&quot; xml:lang=&quot;en&quot; lang=&quot;en&quot;&gt;\r\n&lt;head&gt;\r\n    &lt;title&gt;Create Plain Old PHP Object&lt;\/title&gt;\r\n&lt;\/head&gt;\r\n&lt;body&gt;\r\n&lt;h1&gt;Create Plain Old PHP Object&lt;\/h1&gt;\r\n&lt;form method=&quot;post&quot; action=&quot;&lt;?php echo $_SERVER&#x5B;&quot;SCRIPT_NAME&quot;];?&gt;&quot;&gt;\r\n&lt;fieldset&gt;\r\n&lt;label&gt;Class name: &lt;\/label&gt;\r\n&lt;input type=&quot;text&quot; name=&quot;text_class_name&quot; value=&quot;&lt;?php echo $className;?&gt;&quot;\/&gt;\r\n&lt;\/fieldset&gt;\r\n&lt;fieldset&gt;\r\n&lt;label&gt;Variable name(s), comma-delimited: &lt;\/label&gt;\r\n&lt;input type=&quot;text&quot; name=&quot;text_variable_names&quot; value=&quot;&lt;?php echo $variableNames;?&gt;&quot;\/&gt;\r\n&lt;\/fieldset&gt;\r\n&lt;input type=&quot;submit&quot; id=&quot;submitButton&quot; name=&quot;submitButton&quot; value=&quot;Submit&quot;\/&gt;\r\n&lt;\/form&gt;\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;\r\n<\/pre>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-20\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-20&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-20&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F124&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>Throughout my programming years, I observed similar trends in code structures and I felt that being able to generate them automatically will greatly reduce development time. <\/p>\n<p>Although there are many code generation software on the web, coding one for your own usage can be simpler and more convenient, especially when you had written custom functions that your generated codes will utilize. <\/p>\n<p>In this post, I shall discuss my recent experience in creating a PHP code generator for my own usage. <\/p>\n","protected":false},"author":1,"featured_media":1202,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[36,13],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/PHP-logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-20","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/124"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=124"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/124\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1202"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=124"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=124"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=124"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}