Our blog

 

Zend Framework Template Renamer Script

Bit hard to describe this one, but if you use Zend Framework along with the MVC functionality, and you also use base classes for your controllers, models etc, you may find that for each controller, model etc the files are pretty much the same apart from the names of the files and the classes.

If this sounds familiar then you might be interested in this little script.

Put the script in a folder that contains a sub folder called TEMPLATE. In the template folder have a skeleton template with controllers, models and views folders. If you wanted to replicate this basic structure x amount of times for each of your controllers, this script will make that procedure a breeze.

There may be other applications for this little utility as well.

(now updated to accepted a # separated list of replacements - create your entire structure in one move :D )

PHP:
  1. <?php
  2. /* This is a simple script designed to be run in a folder that contains a TEMPLATE folder
  3. *
  4. * the template folder shoudl contain  your folder structure for your zend framework app.
  5. *
  6. * Normally this will be something like the format:
  7. *
  8. * controllers/item.php
  9. * models/item.php
  10. * models/db_table/item.php
  11. * views/scripts/
  12. *  blah.php
  13. *  yada.php
  14. *  etc.php
  15. *
  16. * The script will take this template of folders and files and will find and will create a new folder structure in which all the filenames have been changed and within the files, a batch of finds and replaces have been done.
  17. *
  18. * The idea is that this then gives you a starting point for your ZF app. This works especially well if each controller, model etc inherits from a custom base_controller or base_model.
  19. *
  20. * hope it helps someone out :-)
  21. *
  22. * Joseph
  23. *
  24. * edmondscommerce.co.uk
  25. *
  26. * */
  27.  
  28.  
  29. if(!isset($_GET['replaceme'])){
  30. ?>
  31.     <form>
  32. <h3>Set Find and Replace - Please Input Upper Cased - lower cased will be automatically replaced as well</h3>
  33. <b>Find:</b> <input name="findme"> <b>Replace:</b> <input name="replaceme"> <input type="submit" value="go"></form>
  34. <h3>To Do A List of Replacemes - use a # separated list</h3>
  35. <?php
  36.     exit;
  37. }
  38. $fm = $_GET['findme'];
  39. $rms = explode('#', $_GET['replaceme']);
  40.  
  41. error_reporting(E_ALL ^ E_NOTICE);
  42.  
  43. $debug = true;
  44.  
  45. /*
  46. $fm = 'findMe';
  47. $rm = 'replaceMe';
  48. */
  49.  
  50.  
  51.  
  52. /*get root current working directory*/
  53. $cwd = getcwd();
  54.  
  55. /*output folder */
  56. $of = 'OUTPUT';
  57. if(is_dir($of)){
  58.     delete($of);
  59. }
  60. mkdir($of);
  61.  
  62.  
  63. foreach($rms as $k=>$rm){
  64.     echo '<h1>' . $rm . '</h1>';
  65.     /* First create a sub folder to put our new structure in */
  66.  
  67.  
  68.     /*template path */
  69.     $template = $cwd . '/TEMPLATE/';
  70.  
  71.     /*copy template to output */
  72.     //if($k === 0){
  73.         dir_copy('TEMPLATE', $of);
  74.     //}
  75.    
  76.     /* Now get output structure */
  77.     $dirlist = dir_list($of);
  78.     dbug($dirlist);
  79.  
  80.     /*now jump into the output folder */
  81.     chdir($of);
  82.  
  83.     /*Now loop through, rename the file and then find and replace the contents */
  84.     replace_rename($dirlist, $fm, $rm);
  85.  
  86.     /* Jump back to the main cwd */
  87.     chdir($cwd);
  88. }
  89.  
  90.  
  91. ######## FUNCTIONS #########
  92.  
  93. function replace_rename($array, $fm, $rm){
  94.     $chdir = getcwd();
  95.     foreach($array as $k=>$v){
  96.         if(is_int($k)){
  97.             //its a file
  98.             $newfile = str_replace(strtolower($fm), strtolower($rm), str_replace($fm, $rm, $v));
  99.             h3("Renaming $v to $newfile");
  100.             rename($v, $newfile);
  101.             done();
  102.             h3("Replacing Contents of $newfile");
  103.             $fc = file_get_contents($newfile);
  104.             if(empty($fc)){
  105.                 err("$newfile empty");
  106.                 exit;
  107.             }
  108.             if(!stristr($fc, $fm)){
  109.                 err("$fm not found in this file... should it have been?");
  110.             }
  111.             $newcontents = str_replace(strtolower($fm), strtolower($rm), str_replace($fm, $rm, $fc));
  112.             file_put_contents($newfile, $newcontents);   
  113.             done()
  114.         }else{
  115.             $newfolder = str_replace(strtolower($fm), strtolower($rm), str_replace($fm, $rm, $k));
  116.             h3("Renaming $k to $newfile");
  117.             rename($k, $newfolder);
  118.             done();
  119.             $jumpin = $chdir . '/' . $newfolder;
  120.             h3("Jumping to $jumpin");
  121.             chdir($jumpin);
  122.             done();
  123.             //its a folder
  124.             h3("Now Recursing into $k");
  125.             echo '<blockquote>';
  126.             replace_rename($v, $fm, $rm);
  127.             echo '</blockquote>';
  128.             done();
  129.             chdir($chdir);
  130.         }   
  131.     }
  132.     chdir($chdir);
  133. }
  134.  
  135.  
  136. // http://uk3.php.net/copy
  137. function dir_copy($srcdir, $dstdir, $offset = '', $verbose = true)
  138. {
  139.     // A function to copy files from one directory to another one, including subdirectories and
  140.     // nonexisting or newer files. Function returns number of files copied.
  141.     // This function is PHP implementation of Windows xcopy  A:\dir1\* B:\dir2 /D /E /F /H /R /Y
  142.     // Syntaxis: [$returnstring =] dircopy($sourcedirectory, $destinationdirectory [, $offset] [, $verbose]);
  143.     // Example: $num = dircopy('A:\dir1', 'B:\dir2', 1);
  144.  
  145.     // Original by SkyEye.  Remake by AngelKiha.
  146.     // Linux compatibility by marajax.
  147.     // ([danbrown AT php DOT net): *NIX-compatibility noted by Belandi.]
  148.     // Offset count added for the possibilty that it somehow miscounts your files.  This is NOT required.
  149.     // Remake returns an explodable string with comma differentiables, in the order of:
  150.     // Number copied files, Number of files which failed to copy, Total size (in bytes) of the copied files,
  151.     // and the files which fail to copy.  Example: 5,2,150000,\SOMEPATH\SOMEFILE.EXT|\SOMEPATH\SOMEOTHERFILE.EXT
  152.     // If you feel adventurous, or have an error reporting system that can log the failed copy files, they can be
  153.     // exploded using the | differentiable, after exploding the result string.
  154.     //
  155.     if(!isset($offset)) $offset=0;
  156.     $num = 0;
  157.     $fail = 0;
  158.     $sizetotal = 0;
  159.     $fifail = '';
  160.     if(!is_dir($dstdir)) mkdir($dstdir);
  161.     if($curdir = opendir($srcdir)) {
  162.         while($file = readdir($curdir)) {
  163.             if($file != '.' && $file != '..') {
  164. //                $srcfile = $srcdir . '\\' . $file;    # deleted by marajax
  165. //                $dstfile = $dstdir . '\\' . $file;    # deleted by marajax
  166.                 $srcfile = $srcdir . '/' . $file;    # added by marajax
  167.                 $dstfile = $dstdir . '/' . $file;    # added by marajax
  168.                 if(is_file($srcfile)) {
  169.                     if(is_file($dstfile)) $ow = filemtime($srcfile) - filemtime($dstfile); else $ow = 1;
  170.                     if($ow> 0) {
  171.                         if($verbose) echo "Copying '$srcfile' to '$dstfile'...<br />";
  172.                         if(copy($srcfile, $dstfile)) {
  173.                             touch($dstfile, filemtime($srcfile)); $num++;
  174.                             chmod($dstfile, 0777);    # added by marajax
  175.                             $sizetotal = ($sizetotal + filesize($dstfile));
  176.                             if($verbose) echo "OK\n";
  177.                         }
  178.                         else {
  179.                             echo "Error: File '$srcfile' could not be copied!<br />\n";
  180.                             $fail++;
  181.                             $fifail = $fifail.$srcfile.'|';
  182.                         }
  183.                     }
  184.                 }
  185.                 else if(is_dir($srcfile)) {
  186.                     $res = explode(',',$ret);
  187. //                    $ret = dircopy($srcfile, $dstfile, $verbose); # deleted by patrick
  188.                     $ret = dir_copy($srcfile, $dstfile, $verbose); # added by patrick
  189.                     $mod = explode(',',$ret);
  190.                     $imp = array($res[0] + $mod[0],$mod[1] + $res[1],$mod[2] + $res[2],$mod[3].$res[3]);
  191.                     $ret = implode(',',$imp);
  192.                 }
  193.             }
  194.         }
  195.         closedir($curdir);
  196.     }
  197.     $red = explode(',',$ret);
  198.     $ret = ($num + $red[0]).','.(($fail-$offset) + $red[1]).','.($sizetotal + $red[2]).','.$fifail.$red[3];
  199.     return $ret;
  200. }
  201.  
  202.  
  203.  
  204.  
  205. function dir_list($directory){
  206.     //echo $directory;
  207.     if ($handle = opendir($directory)) {
  208.         while (false !== ($file = readdir($handle))) {
  209.             if($file != '.' && $file != '..'){
  210.                 if(is_dir($directory . '/' . $file)){
  211.                     $return[$file]=dir_list($directory . '/' . $file . '/');
  212.                 }else{
  213.                     $return[] = $file;
  214.                 }
  215.             }
  216.         }
  217.         closedir($handle);
  218.         return $return;
  219.     }else{   
  220.         return false;
  221.     }
  222. }
  223.  
  224. //recursive delete file/folder
  225. function delete($dirname, $folder_empty = 'delete'){
  226.     // Sanity check
  227.     if (!file_exists($dirname)) {
  228.         echo '<h3 style="color: red;">File ' . $dirname . ' does not exist</h3>';
  229.         //bottom();
  230.         return false;
  231.     }
  232.  
  233.     // Simple delete for a file
  234.     if (is_file($dirname)) {
  235.         return unlink($dirname);
  236.     }
  237.  
  238.     // Loop through the folder
  239.     $dir = dir($dirname);
  240.     while (false !== $entry = $dir->read()) {
  241.         // Skip pointers
  242.         if ($entry == '.' || $entry == '..') {
  243.             continue;
  244.         }
  245.         // Recurse
  246.         delete("$dirname/$entry");
  247.     }// end while looping
  248.  
  249.     // Clean up
  250.     $dir->close();
  251.     if($folder_empty == 'delete'){
  252.         return rmdir($dirname);
  253.     }else{
  254.         //just empty the folder, don't actually delete it
  255.         return true;
  256.     }
  257. }
  258.  
  259. //DEbug Functions
  260.  
  261. //convert tabs to spaces
  262. function tab2space($text, $spaces = 4){
  263.     $text = str_replace('  ', '&nbsp;&nbsp;&nbsp;&nbsp;', $text);
  264.     $text = str_replace("\t", '&nbsp;&nbsp;&nbsp;&nbsp;', $text);
  265.     return $text;
  266. }
  267.  
  268. //return name of variable passed by reference
  269. function vname(&$var, $scope=false){
  270.     if($scope) $vals = $scope;
  271.     else      $vals = $GLOBALS;
  272.     $old = $var;
  273.     $new = 'THISONE';
  274.     $var = $new;
  275.     $vname = false;
  276.     foreach($vals as $key => $val) {
  277.         if($val !=='var'){
  278.             if($val === $new) $vname = $key;
  279.         }
  280.     }
  281.     $var = $old;
  282.     return $vname;
  283.   }
  284.  
  285.  
  286. function dbug(&$item, $scope=false){
  287.     global $debug;
  288.     if(!$debug){
  289.         return false;
  290.     }
  291.     $vname = vname(&$item,$scope);
  292.     echo '<hr><h3>Debug Info: $' . $vname  . '</h3>' . tab2space(nl2br(htmlentities(var_export($item, true)))) . '<hr>';   
  293.     flush();
  294. }
  295.  
  296. function done(){
  297.     echo '<h3 style="color: green;">Done..</h3>';
  298. }
  299.  
  300. function h3($text){
  301.     echo '<h3>' . $text . '</h3>';
  302.     flush();
  303. }
  304.  
  305. function err($text){
  306.     echo '<h3 style="color: red;">' . $text . '</h3>';
  307. }

More...

More Reading:

2 Comments

gabriel solomon
March 6th, 2009

I usually resort to global controllers for this problem. i have a controllers dir in my aplication folder where i put them and the controllers from the modules directory extend them.

 

admin
March 6th, 2009

Hi Gabriel

I do something similar I think, however I lets say I have a project with 10 tables and I want to use my baseCrudController on these ten tables I have to go and create a whole bunch of files that are basically empty initially

I was either going to spend an hour messing about creating files, or create a script to do it for me - and here it is :-)

 

 

Leave a Reply