Skip to content

Instantly share code, notes, and snippets.

@remluben
Created November 8, 2013 21:43
Show Gist options
  • Save remluben/7378160 to your computer and use it in GitHub Desktop.
Save remluben/7378160 to your computer and use it in GitHub Desktop.
Shellscript: PHP Getter & Setter Generator
#!/usr/bin/php
<?php
/*
* Quelle: http://blog.dennis.io/php-gettersetter-generator/
*/
if (!is_file($argv[2]))
die('Use this way: '.$argv[0].' <class_name> <path_to_your_class`s_php_file>'."\n");
require_once($argv[2]);
$class = new $argv[1]();
$reflection = new ReflectionClass($argv[1]);
$fields = $reflection->getProperties(
ReflectionProperty::IS_PRIVATE
| ReflectionProperty::IS_PROTECTED
);
$code = '';
foreach ($fields AS $f) {
$memberName = $f->getName();
$name = $f->getName();
if (strpos($name, '_') === 0) {
$name = substr($name, 1);
}
$methodNamePart = ucfirst($name);
$className = $f->class;
$message = "Type of $className's member $$memberName:";
print $message;
// flush();
// ob_flush();
$type = trim( fgets( STDIN ) );
// TODO: check for allowed types
if ( $type === '' ) { // no user input
$type = '{type}';
}
$code .= <<<CODE
/**
* @return $type
*/
public function get$methodNamePart()
{
return \$this->$memberName;
}
/**
* @param $type $$name
* @return $className
*/
public function set$methodNamePart($$name)
{
\$this->$memberName = $$name;
return \$this;
}
CODE;
// // getter
// echo 'public function get'.ucfirst($name).'()'."\n";
// echo '{'."\n";
// echo "\t".'return $this->'.$f->getName().';'."\n";
// echo '}'."\n";
// // setter
// echo 'public function set'.ucfirst($name).'($' . $name . ')'."\n";
// echo '{'."\n";
// echo "\t".'$this->'.$f->getName().' = $' . $name . ';'."\n";
// echo '}'."\n\n";
}
echo $code;
echo 'Generated getter and setter for '.count($fields).' fields'."\n\n";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment